diff --git a/.claude/settings.local.json b/.claude/settings.local.json new file mode 100644 index 000000000..e20c0031d --- /dev/null +++ b/.claude/settings.local.json @@ -0,0 +1,12 @@ +{ + "permissions": { + "allow": [ + "Bash(find:*)", + "Bash(python3:*)", + "Bash(python:*)", + "Bash(chmod +x:*)", + "Bash(grep:*)", + "Bash(git diff:*)" + ] + } +} diff --git a/examples/twilio_campaign_example.py b/examples/twilio_campaign_example.py new file mode 100755 index 000000000..123606f48 --- /dev/null +++ b/examples/twilio_campaign_example.py @@ -0,0 +1,807 @@ +#!/usr/bin/env python +""" +Twilio Messaging Campaign Example + +This comprehensive example demonstrates how to: +1. Create messaging services with status callbacks +2. Configure link shortening domains and TLS certificates +3. Send campaign messages with rate limiting and retry logic +4. Review campaign performance with pagination +5. Handle webhooks for delivery status and click tracking + +Requirements: + pip install twilio flask + +Environment Variables: + TWILIO_ACCOUNT_SID - Your Twilio Account SID + TWILIO_AUTH_TOKEN - Your Twilio Auth Token + +Usage: + # Run the full campaign example + python examples/twilio_campaign_example.py + + # Run webhook server only + python examples/twilio_campaign_example.py --webhooks-only +""" + +import os +import sys +import time +import logging +from datetime import datetime, timedelta +from typing import List, Dict, Optional +from collections import defaultdict + +from twilio.rest import Client +from twilio.base.exceptions import TwilioRestException +from twilio.request_validator import RequestValidator + + +# ============================================================================ +# Section 1: Configuration & Setup +# ============================================================================ + +# Configure logging +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' +) +logger = logging.getLogger(__name__) + +# Twilio credentials from environment +ACCOUNT_SID = os.environ.get('TWILIO_ACCOUNT_SID') +AUTH_TOKEN = os.environ.get('TWILIO_AUTH_TOKEN') +TWILIO_PHONE_NUMBER = os.environ.get('TWILIO_PHONE_NUMBER') +PHONE_NUMBER_SID = os.environ.get('PHONE_NUMBER_SID') + +if not ACCOUNT_SID or not AUTH_TOKEN: + logger.error("Missing TWILIO_ACCOUNT_SID or TWILIO_AUTH_TOKEN environment variables") + sys.exit(1) + +# Initialize Twilio client +client = Client(ACCOUNT_SID, AUTH_TOKEN) + + +# ============================================================================ +# Section 2: Messaging Service Infrastructure +# ============================================================================ + +def create_messaging_service( + friendly_name: str, + status_callback_url: Optional[str] = None, + usecase: str = 'marketing', + sticky_sender: bool = True +) -> Dict: + """ + Create a Twilio messaging service for campaign messages. + + Args: + friendly_name: Human-readable name for the service + status_callback_url: URL for message status updates (delivered, failed, etc.) + usecase: Service use case ('marketing', '2fa', 'notifications', etc.) + sticky_sender: Whether to use the same sender for all messages to a recipient + + Returns: + Dictionary containing service details (sid, friendly_name, etc.) + """ + logger.info(f"Creating messaging service: {friendly_name}") + + try: + service = client.messaging.v1.services.create( + friendly_name=friendly_name, + status_callback=status_callback_url, + usecase=usecase, + sticky_sender=sticky_sender + ) + + logger.info(f"✓ Messaging service created: {service.sid}") + return { + 'sid': service.sid, + 'friendly_name': service.friendly_name, + 'status_callback': service.status_callback, + 'usecase': service.usecase + } + except TwilioRestException as e: + logger.error(f"Failed to create messaging service: {e.msg} (Code: {e.code})") + raise + + +def add_phone_number_to_service(service_sid: str, phone_number_sid: str) -> bool: + """ + Add a phone number to a messaging service. + + Args: + service_sid: The messaging service SID + phone_number_sid: The phone number SID to add + + Returns: + True if successful + """ + logger.info(f"Adding phone number {phone_number_sid} to service {service_sid}") + + try: + client.messaging.v1.services(service_sid).phone_numbers.create( + phone_number_sid=phone_number_sid + ) + logger.info("✓ Phone number added to service") + return True + except TwilioRestException as e: + logger.error(f"Failed to add phone number: {e.msg} (Code: {e.code})") + raise + + +# ============================================================================ +# Section 3: Link Shortening Domain Setup +# ============================================================================ + +def upload_tls_certificate(domain_sid: str, tls_cert_pem: str) -> Dict: + """ + Upload a TLS certificate for link shortening domain. + + Args: + domain_sid: The domain SID + tls_cert_pem: PEM-encoded TLS certificate content + + Returns: + Dictionary containing certificate details + """ + logger.info(f"Uploading TLS certificate for domain: {domain_sid}") + + try: + cert = client.messaging.v1.domain_certs.get(domain_sid).update( + tls_cert=tls_cert_pem + ) + + logger.info("✓ TLS certificate uploaded successfully") + return { + 'domain_sid': cert.domain_sid, + 'date_updated': cert.date_updated + } + except TwilioRestException as e: + logger.error(f"Failed to upload certificate: {e.msg} (Code: {e.code})") + raise + + +def configure_link_shortening_domain( + domain_sid: str, + callback_url: str, + fallback_url: Optional[str] = None +) -> Dict: + """ + Configure link shortening domain with click tracking callbacks. + + Args: + domain_sid: The domain SID + callback_url: URL to receive click tracking events + fallback_url: Fallback URL if callback fails + + Returns: + Dictionary containing domain configuration + """ + logger.info(f"Configuring link shortening domain: {domain_sid}") + + try: + config = client.messaging.v1.domain_config.get(domain_sid).update( + callback_url=callback_url, + fallback_url=fallback_url + ) + + logger.info("✓ Domain configuration updated") + return { + 'domain_sid': config.domain_sid, + 'callback_url': config.callback_url, + 'fallback_url': config.fallback_url + } + except TwilioRestException as e: + logger.error(f"Failed to configure domain: {e.msg} (Code: {e.code})") + raise + + +# ============================================================================ +# Section 4: Campaign Message Sending +# ============================================================================ + +class RateLimitHandler: + """ + Handle rate limiting (HTTP 429) with exponential backoff retry logic. + """ + + def __init__(self, max_retries: int = 5, initial_delay: float = 1.0): + self.max_retries = max_retries + self.initial_delay = initial_delay + + def send_with_retry(self, send_func, *args, **kwargs): + """ + Execute a send function with exponential backoff on rate limit errors. + + Args: + send_func: Function to call for sending message + *args, **kwargs: Arguments to pass to send_func + + Returns: + Message object if successful + + Raises: + TwilioRestException: If all retries fail or non-retryable error occurs + """ + delay = self.initial_delay + + for attempt in range(self.max_retries): + try: + return send_func(*args, **kwargs) + + except TwilioRestException as e: + # Handle rate limiting (429) + if e.status == 429: + if attempt < self.max_retries - 1: + logger.warning( + f"Rate limited (429). Retrying in {delay}s " + f"(attempt {attempt + 1}/{self.max_retries})" + ) + time.sleep(delay) + delay *= 2 # Exponential backoff + continue + else: + logger.error("Max retries reached for rate limiting") + raise + + # Handle unreachable destination (30003) + elif e.code == 30003: + logger.error(f"Unreachable destination: {e.msg}") + raise + + # Handle landline/unreachable carrier (30006) + elif e.code == 30006: + logger.error(f"Landline or unreachable carrier: {e.msg}") + raise + + # Other errors - don't retry + else: + logger.error(f"Message send failed: {e.msg} (Code: {e.code})") + raise + + raise TwilioRestException( + status=429, + uri="", + msg="Max retries exceeded for rate limiting" + ) + + +def send_campaign_message( + to: str, + body: str, + messaging_service_sid: str, + status_callback: Optional[str] = None, + shorten_urls: bool = True, + rate_limit_handler: Optional[RateLimitHandler] = None +) -> Dict: + """ + Send a campaign message with rate limiting support. + + Args: + to: Recipient phone number (E.164 format) + body: Message text content + messaging_service_sid: SID of the messaging service to use + status_callback: URL for delivery status updates + shorten_urls: Whether to shorten URLs in message + rate_limit_handler: RateLimitHandler instance for retry logic + + Returns: + Dictionary containing message details (sid, status, etc.) + """ + if rate_limit_handler is None: + rate_limit_handler = RateLimitHandler() + + def _send(): + return client.messages.create( + messaging_service_sid=messaging_service_sid, + to=to, + body=body, + status_callback=status_callback, + shorten_urls=shorten_urls + ) + + try: + message = rate_limit_handler.send_with_retry(_send) + + logger.info(f"✓ Message sent to {to}: {message.sid} (Status: {message.status})") + return { + 'sid': message.sid, + 'to': message.to, + 'status': message.status, + 'date_created': message.date_created + } + except TwilioRestException as e: + logger.error(f"Failed to send message to {to}: {e.msg}") + return { + 'sid': None, + 'to': to, + 'status': 'failed', + 'error_code': e.code, + 'error_message': e.msg + } + + +def send_bulk_campaign( + recipients: List[str], + message_body: str, + messaging_service_sid: str, + batch_delay: float = 0.1 +) -> Dict: + """ + Send messages to multiple recipients with rate limiting. + + Args: + recipients: List of recipient phone numbers + message_body: Message text to send + messaging_service_sid: SID of the messaging service + batch_delay: Delay between messages (seconds) + + Returns: + Dictionary with campaign statistics + """ + logger.info(f"Starting bulk campaign to {len(recipients)} recipients") + + rate_handler = RateLimitHandler(max_retries=5, initial_delay=1.0) + results = { + 'total': len(recipients), + 'sent': 0, + 'failed': 0, + 'messages': [] + } + + for i, recipient in enumerate(recipients, 1): + logger.info(f"Sending message {i}/{len(recipients)} to {recipient}") + + result = send_campaign_message( + to=recipient, + body=message_body, + messaging_service_sid=messaging_service_sid, + rate_limit_handler=rate_handler + ) + + results['messages'].append(result) + + if result['status'] != 'failed': + results['sent'] += 1 + else: + results['failed'] += 1 + + # Small delay between messages + if i < len(recipients): + time.sleep(batch_delay) + + logger.info( + f"✓ Campaign complete: {results['sent']} sent, {results['failed']} failed" + ) + return results + + +# ============================================================================ +# Section 5: Campaign Performance Review +# ============================================================================ + +def get_campaign_messages( + from_number: Optional[str] = None, + to_number: Optional[str] = None, + date_sent_after: Optional[datetime] = None, + date_sent_before: Optional[datetime] = None, + messaging_service_sid: Optional[str] = None, + limit: int = 1000 +) -> List[Dict]: + """ + Retrieve campaign messages with pagination support. + + Note: The Twilio Messages API stream() method does NOT support filtering by + messaging_service_sid directly. It only supports: to, from_, date_sent filters. + + If you need to filter by messaging service, you have two options: + 1. Use from_number to filter by a specific sender from your messaging service + 2. Fetch all messages and filter in-memory by messaging_service_sid (less efficient) + + Args: + from_number: Filter by sender phone number (E.164 format, e.g., "+15551234567") + to_number: Filter by recipient phone number (E.164 format) + date_sent_after: Only include messages sent after this date + date_sent_before: Only include messages sent before this date + messaging_service_sid: If provided, filter results in-memory by this messaging service SID + limit: Maximum number of messages to retrieve from API (before in-memory filtering) + + Returns: + List of message dictionaries + + Example: + # Get messages from a specific phone number in your messaging service + messages = get_campaign_messages( + from_number="+15551234567", + date_sent_after=datetime(2024, 1, 1) + ) + + # Get all account messages and filter by messaging service (slower) + messages = get_campaign_messages( + messaging_service_sid="MGxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + date_sent_after=datetime(2024, 1, 1) + ) + """ + logger.info("Fetching campaign messages...") + + messages = [] + + try: + # Use stream() for automatic pagination + # WARNING: stream() does NOT support messaging_service_sid parameter + for message in client.messages.stream( + to=to_number, + from_=from_number, + date_sent_after=date_sent_after, + date_sent_before=date_sent_before, + page_size=100, + limit=limit + ): + # Filter by messaging_service_sid in memory if provided + if messaging_service_sid and message.messaging_service_sid != messaging_service_sid: + continue + + messages.append({ + 'sid': message.sid, + 'to': message.to, + 'from': message.from_, + 'body': message.body, + 'status': message.status, + 'date_sent': message.date_sent, + 'date_created': message.date_created, + 'error_code': message.error_code, + 'error_message': message.error_message, + 'num_segments': message.num_segments, + 'price': message.price, + 'price_unit': message.price_unit, + 'messaging_service_sid': message.messaging_service_sid + }) + + logger.info(f"✓ Retrieved {len(messages)} messages") + return messages + + except TwilioRestException as e: + logger.error(f"Failed to fetch messages: {e.msg} (Code: {e.code})") + raise + + +def calculate_campaign_statistics(messages: List[Dict]) -> Dict: + """ + Calculate performance statistics from campaign messages. + + Args: + messages: List of message dictionaries from get_campaign_messages() + + Returns: + Dictionary with campaign statistics + """ + stats = { + 'total_messages': len(messages), + 'by_status': defaultdict(int), + 'total_segments': 0, + 'total_cost': 0.0, + 'error_breakdown': defaultdict(int), + 'delivery_rate': 0.0 + } + + for msg in messages: + # Count by status + stats['by_status'][msg['status']] += 1 + + # Sum segments + if msg['num_segments']: + stats['total_segments'] += int(msg['num_segments']) + + # Sum costs + if msg['price']: + stats['total_cost'] += abs(float(msg['price'])) + + # Error breakdown + if msg['error_code']: + stats['error_breakdown'][msg['error_code']] += 1 + + # Calculate delivery rate + delivered = stats['by_status'].get('delivered', 0) + if stats['total_messages'] > 0: + stats['delivery_rate'] = (delivered / stats['total_messages']) * 100 + + return dict(stats) + + +def print_campaign_report(stats: Dict): + """ + Print a formatted campaign performance report. + + Args: + stats: Statistics dictionary from calculate_campaign_statistics() + """ + print("\n" + "=" * 60) + print("CAMPAIGN PERFORMANCE REPORT") + print("=" * 60) + + print(f"\nTotal Messages: {stats['total_messages']}") + print(f"Total Segments: {stats['total_segments']}") + print(f"Total Cost: ${stats['total_cost']:.4f} {list(stats.get('messages', [{}]))[0].get('price_unit', 'USD') if stats.get('messages') else 'USD'}") + print(f"Delivery Rate: {stats['delivery_rate']:.2f}%") + + print("\nStatus Breakdown:") + for status, count in sorted(stats['by_status'].items()): + percentage = (count / stats['total_messages']) * 100 + print(f" {status.capitalize():.<20} {count:>5} ({percentage:>5.1f}%)") + + if stats['error_breakdown']: + print("\nError Code Breakdown:") + for error_code, count in sorted(stats['error_breakdown'].items()): + print(f" Error {error_code}{'.'*10} {count:>5}") + + print("\n" + "=" * 60 + "\n") + + +# ============================================================================ +# Section 6: Webhook Handlers +# ============================================================================ + +def validate_twilio_request(url: str, params: Dict, signature: str) -> bool: + """ + Validate that a webhook request came from Twilio. + + Args: + url: Full URL of the webhook endpoint + params: Request parameters (POST body or query string) + signature: X-Twilio-Signature header value + + Returns: + True if request is valid, False otherwise + """ + validator = RequestValidator(AUTH_TOKEN) + return validator.validate(url, params, signature) + + +def create_webhook_app(): + """ + Create a Flask app with webhook handlers for status callbacks and click tracking. + + Returns: + Flask application instance + """ + try: + from flask import Flask, request, jsonify + except ImportError: + logger.error("Flask is not installed. Run: pip install flask") + return None + + app = Flask(__name__) + + @app.route('/webhooks/status', methods=['POST']) + def status_callback(): + """ + Handle message status updates (queued, sent, delivered, failed, etc.). + """ + # Validate request signature + signature = request.headers.get('X-Twilio-Signature', '') + url = request.url + + if not validate_twilio_request(url, request.form.to_dict(), signature): + logger.warning(f"Invalid webhook signature from {request.remote_addr}") + return jsonify({'error': 'Invalid signature'}), 403 + + # Extract status update data + message_sid = request.form.get('MessageSid') + message_status = request.form.get('MessageStatus') + to = request.form.get('To') + error_code = request.form.get('ErrorCode') + error_message = request.form.get('ErrorMessage') + + logger.info( + f"Status update: {message_sid} to {to} - " + f"Status: {message_status}" + ) + + if error_code: + logger.error( + f"Message {message_sid} error: {error_message} " + f"(Code: {error_code})" + ) + + # Here you would typically: + # - Update database with message status + # - Trigger alerts for failed messages + # - Update campaign analytics + + return jsonify({'status': 'received'}), 200 + + @app.route('/webhooks/click-tracking', methods=['POST']) + def click_tracking(): + """ + Handle link click tracking events. + """ + # Validate request signature + signature = request.headers.get('X-Twilio-Signature', '') + url = request.url + + if not validate_twilio_request(url, request.form.to_dict(), signature): + logger.warning(f"Invalid webhook signature from {request.remote_addr}") + return jsonify({'error': 'Invalid signature'}), 403 + + # Extract click tracking data + message_sid = request.form.get('MessageSid') + link_clicked = request.form.get('LinkUrl') + recipient = request.form.get('To') + click_time = request.form.get('Timestamp') + + logger.info( + f"Link clicked: {link_clicked} in message {message_sid} " + f"by {recipient} at {click_time}" + ) + + # Here you would typically: + # - Store click event in analytics database + # - Update campaign engagement metrics + # - Trigger follow-up actions + + return jsonify({'status': 'received'}), 200 + + @app.route('/health', methods=['GET']) + def health(): + """Health check endpoint.""" + return jsonify({'status': 'healthy'}), 200 + + return app + + +def run_webhook_server(host: str = '0.0.0.0', port: int = 5000): + """ + Start the webhook server. + + Args: + host: Host to bind to + port: Port to listen on + + Note: + For production, use ngrok or similar to expose webhooks: + ngrok http 5000 + Then configure Twilio with your ngrok URL. + """ + app = create_webhook_app() + + if app is None: + return + + logger.info(f"Starting webhook server on {host}:{port}") + logger.info( + "For local development, expose this with ngrok:\n" + f" ngrok http {port}\n" + "Then configure Twilio webhooks with your ngrok URL" + ) + + app.run(host=host, port=port, debug=False) + + +# ============================================================================ +# Section 7: Main Execution - Complete Workflow +# ============================================================================ + +def main(): + """ + Run a complete messaging campaign demonstration. + """ + print("\n" + "=" * 60) + print("TWILIO MESSAGING CAMPAIGN EXAMPLE") + print("=" * 60 + "\n") + + try: + # Step 1: Create messaging service + print("Step 1: Creating messaging service...") + service = create_messaging_service( + friendly_name="Marketing Campaign Service", + status_callback_url="https://shaggy-heads-join.loca.lt/webhooks/status", + usecase='marketing', + sticky_sender=True + ) + service_sid = service['sid'] + print(f"✓ Service created: {service_sid}\n") + + # Optional: Add phone numbers to the service + # phone_number_sid = "PN..." # Your Twilio phone number SID + add_phone_number_to_service(service_sid, PHONE_NUMBER_SID) + + # Step 2: Configure link shortening (optional - requires domain) + print("Step 2: Link shortening configuration (skipped - requires domain)") + print(" To enable link shortening:") + print(" 1. Configure a domain in Twilio Console") + print(" 2. Upload TLS certificate using upload_tls_certificate()") + print(" 3. Configure callbacks using configure_link_shortening_domain()\n") + + # Step 3: Send campaign messages + print("Step 3: Sending campaign messages...") + + # Example recipients (replace with real phone numbers for testing) + recipients = [ + "+1234567890", # Replace with real numbers + "+1234567891", + "+1234567892" + ] + + message_body = ( + "Hello! Check out our new product launch: " + "https://example.com/campaign" + ) + + # Uncomment to actually send messages + # campaign_results = send_bulk_campaign( + # recipients=recipients, + # message_body=message_body, + # messaging_service_sid=service_sid, + # batch_delay=0.1 + # ) + + print(" (Skipped - update recipients list with real numbers to test)\n") + + # Step 4: Review campaign performance + print("Step 4: Reviewing campaign performance...") + + # Fetch messages from last 24 hours + # Note: For better performance, use from_number instead of messaging_service_sid + date_after = datetime.now() - timedelta(days=1) + + # Option A: Filter by messaging service (in-memory filtering - slower) + messages = get_campaign_messages( + messaging_service_sid=service_sid, + date_sent_after=date_after, + limit=1000 + ) + + # Option B: Filter by specific sender number (API filtering - faster) + # Uncomment and replace with your Twilio phone number: + # messages = get_campaign_messages( + # from_number=TWILIO_PHONE_NUMBER, + # date_sent_after=date_after, + # limit=1000 + # ) + + if messages: + stats = calculate_campaign_statistics(messages) + print_campaign_report(stats) + else: + print(" No messages found in the last 24 hours\n") + + # Step 5: Webhook information + print("Step 5: Webhook setup") + print(" To handle status callbacks and click tracking:") + print(" 1. Run webhook server: python examples/twilio_campaign_example.py --webhooks-only") + print(" 2. Expose with ngrok: ngrok http 5000") + print(" 3. Configure Twilio webhooks with your ngrok URL") + print(" - Status callback: https://your-ngrok-url.ngrok.io/webhooks/status") + print(" - Click tracking: https://your-ngrok-url.ngrok.io/webhooks/click-tracking\n") + + print("=" * 60) + print("Campaign demonstration complete!") + print("=" * 60 + "\n") + + except TwilioRestException as e: + logger.error(f"Campaign failed: {e.msg} (Code: {e.code})") + sys.exit(1) + except Exception as e: + logger.error(f"Unexpected error: {e}") + sys.exit(1) + + +if __name__ == '__main__': + import argparse + + parser = argparse.ArgumentParser( + description='Twilio Messaging Campaign Example' + ) + parser.add_argument( + '--webhooks-only', + action='store_true', + help='Run webhook server only (no campaign execution)' + ) + + args = parser.parse_args() + + if args.webhooks_only: + run_webhook_server(host='0.0.0.0', port=5000) + else: + main() diff --git a/twilio/rest/conversations/v2/__init__.py b/twilio/rest/conversations/v2/__init__.py new file mode 100644 index 000000000..15dfe3c11 --- /dev/null +++ b/twilio/rest/conversations/v2/__init__.py @@ -0,0 +1,67 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Maestro (Conversations) + 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.communication import CommunicationList +from twilio.rest.conversations.v2.configuration import ConfigurationList +from twilio.rest.conversations.v2.conversation import ConversationList +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._communications: Optional[CommunicationList] = None + self._configurations: Optional[ConfigurationList] = None + self._conversations: Optional[ConversationList] = None + self._participants: Optional[ParticipantList] = None + + @property + def communications(self) -> CommunicationList: + if self._communications is None: + self._communications = CommunicationList(self) + return self._communications + + @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 participants(self) -> ParticipantList: + if self._participants is None: + self._participants = ParticipantList(self) + return self._participants + + 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 000000000..8a8874194 --- /dev/null +++ b/twilio/rest/conversations/v2/communication.py @@ -0,0 +1,1259 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Maestro (Conversations) + 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 datetime import date, datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator, Protocol +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 CommunicationInstance(InstanceResource): + + 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 { + + "": self.channel, + "": self.confidence, + "": self.engine, + "": [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("start_time") + self.end_time: Optional[datetime] = payload.get("end_time") + + def to_dict(self): + return { + + "": self.text, + "": self.start_time, + "": 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("channel_id") + 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 , + "channel_id": 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("participant_id") + + def to_dict(self): + return { + + "address": self.address, + "channel": self.channel, + "participant_id": 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 , + } + + + + """ + :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 recipients: Communication recipients. + :ivar created_at: Timestamp when this Communication was created. + :ivar updated_at: Timestamp when this Communication was last updated. + """ + + def __init__(self, version: Version, payload:Dict[str, Any], conversation_sid: Optional[str] = None, 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.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._solution = { + "conversation_sid": conversation_sid or self.conversation_sid, + "sid": sid or self.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): + + 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 { + + "": self.channel, + "": self.confidence, + "": self.engine, + "": [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("start_time") + self.end_time: Optional[datetime] = payload.get("end_time") + + def to_dict(self): + return { + + "": self.text, + "": self.start_time, + "": 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("channel_id") + 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 , + "channel_id": 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("participant_id") + + def to_dict(self): + return { + + "address": self.address, + "channel": self.channel, + "participant_id": 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, 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 { + + "": self.channel, + "": self.confidence, + "": self.engine, + "": [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("start_time") + self.end_time: Optional[datetime] = payload.get("end_time") + + def to_dict(self): + return { + + "": self.text, + "": self.start_time, + "": 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("channel_id") + 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 , + "channel_id": 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("participant_id") + + def to_dict(self): + return { + + "address": self.address, + "channel": self.channel, + "participant_id": 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, 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, 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, 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_token: Union[str, object] = values.unset, + 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, 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, 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, self._solution) + + + + def get(self, conversation_sid: str, sid: str) -> CommunicationContext: + """ + Constructs a CommunicationContext + + :param conversation_sid: + :param sid: + """ + return CommunicationContext(self._version, conversation_sid=conversation_sid, sid=sid) + + def __call__(self, conversation_sid: str, sid: str) -> CommunicationContext: + """ + Constructs a CommunicationContext + + :param conversation_sid: + :param sid: + """ + return CommunicationContext(self._version, conversation_sid=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 000000000..55c2ead4d --- /dev/null +++ b/twilio/rest/conversations/v2/configuration.py @@ -0,0 +1,2074 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Maestro (Conversations) + 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 datetime import date, datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator, Protocol +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 ResponseResource(Protocol): + pass + +''' +Nested response model for ConversationsV2CaptureRule +''' +class ConversationsV2CaptureRule: + def __init__(self,_from: str, to: str, metadata: Dict[str, str]): + self._from = _from + self.to = to + self.metadata = metadata + + + +''' +Nested response model for ConversationsV2ChannelSetting +''' +class ConversationsV2ChannelSetting: + def __init__(self,status_timeouts: ConversationsV2StatusTimeouts, capture_rules: List[ConversationsV2CaptureRule]): + self.status_timeouts = status_timeouts + self.capture_rules = capture_rules + + + +''' +Nested response model for ConversationsV2StatusCallbackConfig +''' +class ConversationsV2StatusCallbackConfig: + def __init__(self,url: str, method: str): + self.url = url + self.method = method + + + +''' +Nested response model for ConversationsV2StatusTimeouts +''' +class ConversationsV2StatusTimeouts: + def __init__(self,inactive: int, closed: int): + self.inactive = inactive + self.closed = closed + + + +''' +Nested response model for CreateConfigurationRequest +''' +class CreateConfigurationRequest: + def __init__(self,display_name: str, description: str, conversation_grouping_type: "ConfigurationInstance.str", memory_store_id: str, channel_settings: Dict[str, CreateConfigurationRequestChannelSettingsValue], status_callbacks: List[ConfigurationList.CreateConfigurationRequestStatusCallbacks], intelligence_configuration_ids: List[str]): + self.display_name = display_name + self.description = description + self.conversation_grouping_type = conversation_grouping_type + self.memory_store_id = memory_store_id + self.channel_settings = channel_settings + self.status_callbacks = status_callbacks + self.intelligence_configuration_ids = intelligence_configuration_ids + + + +''' +Nested response model for CreateConfigurationRequestChannelSettingsValue +''' +class CreateConfigurationRequestChannelSettingsValue: + def __init__(self,status_timeouts: CreateConfigurationRequestChannelSettingsValueStatusTimeouts, capture_rules: List[CreateConfigurationRequestChannelSettingsValueCaptureRules]): + self.status_timeouts = status_timeouts + self.capture_rules = capture_rules + + + +''' +Nested response model for CreateConfigurationRequestChannelSettingsValueCaptureRules +''' +class CreateConfigurationRequestChannelSettingsValueCaptureRules: + def __init__(self,_from: str, to: str, metadata: Dict[str, str]): + self._from = _from + self.to = to + self.metadata = metadata + + + +''' +Nested response model for CreateConfigurationRequestChannelSettingsValueStatusTimeouts +''' +class CreateConfigurationRequestChannelSettingsValueStatusTimeouts: + def __init__(self,inactive: int, closed: int): + self.inactive = inactive + self.closed = closed + + + +''' +Nested response model for CreateConfigurationRequestStatusCallbacks +''' +class CreateConfigurationRequestStatusCallbacks: + def __init__(self,url: str, method: "ConfigurationInstance.str"): + self.url = url + self.method = method + + + +''' +Nested response model for UpdateConfigurationRequest +''' +class UpdateConfigurationRequest: + def __init__(self,display_name: str, description: str, conversation_grouping_type: "ConfigurationInstance.str", memory_store_id: str, channel_settings: Dict[str, UpdateConfigurationRequestChannelSettingsValue], status_callbacks: List[ConfigurationList.UpdateConfigurationRequestStatusCallbacks], intelligence_configuration_ids: List[str]): + self.display_name = display_name + self.description = description + self.conversation_grouping_type = conversation_grouping_type + self.memory_store_id = memory_store_id + self.channel_settings = channel_settings + self.status_callbacks = status_callbacks + self.intelligence_configuration_ids = intelligence_configuration_ids + + + +''' +Nested response model for UpdateConfigurationRequestChannelSettingsValue +''' +class UpdateConfigurationRequestChannelSettingsValue: + def __init__(self,status_timeouts: UpdateConfigurationRequestChannelSettingsValueStatusTimeouts, capture_rules: List[UpdateConfigurationRequestChannelSettingsValueCaptureRules]): + self.status_timeouts = status_timeouts + self.capture_rules = capture_rules + + + +''' +Nested response model for UpdateConfigurationRequestChannelSettingsValueCaptureRules +''' +class UpdateConfigurationRequestChannelSettingsValueCaptureRules: + def __init__(self,_from: str, to: str, metadata: Dict[str, str]): + self._from = _from + self.to = to + self.metadata = metadata + + + +''' +Nested response model for UpdateConfigurationRequestChannelSettingsValueStatusTimeouts +''' +class UpdateConfigurationRequestChannelSettingsValueStatusTimeouts: + def __init__(self,inactive: int, closed: int): + self.inactive = inactive + self.closed = closed + + + +''' +Nested response model for UpdateConfigurationRequestStatusCallbacks +''' +class UpdateConfigurationRequestStatusCallbacks: + def __init__(self,url: str, method: "ConfigurationInstance.str"): + self.url = url + self.method = method + + + + + +""" +Response model for ListConfiguration_400_response operations +""" +class ListConfiguration_400_responseResource: + def __init__(self,code: int, message: str, more_info: str, status: int): + """ + Initialize the ListConfiguration_400_responseResource + :param code: Twilio-specific error code + :param message: Error message + :param more_info: Link to Error Code References + :param status: HTTP response status code + + """ + self.code = code + self.message = message + self.more_info = more_info + self.status = status + + +""" +Response model for ListConfiguration_200_response_configurations operations +""" +class ListConfiguration_200_response_configurationsResource: + def __init__(self,id: str, display_name: str, description: str, conversation_grouping_type: str, memory_store_id: str, channel_settings: Dict[str, str], status_callbacks: List[str], intelligence_configuration_ids: List[str], created_at: datetime, updated_at: datetime, version: int): + """ + Initialize the ListConfiguration_200_response_configurationsResource + :param id: Configuration ID. + :param display_name: A human-readable name for the configuration. Limited to 32 characters. + :param 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. + :param conversation_grouping_type: Type of Conversation grouping strategy: - `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. + :param memory_store_id: Memory Store ID for Profile resolution. + :param channel_settings: Channel-specific configuration settings by channel type. Keys should be valid channel types (`VOICE`, `SMS`, `RCS`, `WHATSAPP`, `CHAT`). + :param status_callbacks: List of default webhook configurations applied to Conversations under this Configuration. + :param intelligence_configuration_ids: A list of Conversational Intelligence configuration IDs. + :param created_at: Timestamp when this Configuration was created. + :param updated_at: Timestamp when this Configuration was last updated. + :param version: Version number used for optimistic locking. + + """ + self.id = id + self.display_name = display_name + self.description = description + self.conversation_grouping_type = conversation_grouping_type + self.memory_store_id = memory_store_id + self.channel_settings = channel_settings + self.status_callbacks = status_callbacks + self.intelligence_configuration_ids = intelligence_configuration_ids + self.created_at = created_at + self.updated_at = updated_at + self.version = version + + + + +class ConfigurationInstance(InstanceResource): + + 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 { + + "": self._from, + "": self.to, + "": self.metadata, + } + + 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 { + + "": self.inactive, + "": 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 Maestro (Conversations) uses to assign communications to conversations. + :ivar memory_store_id: The memory store ID that Maestro (Conversations) 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. + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.display_name: Optional[str] = payload.get("display_name") + self.description: Optional[str] = payload.get("description") + self.conversation_grouping_type: Optional["ConfigurationInstance.str"] = payload.get("conversation_grouping_type") + self.memory_store_id: Optional[str] = payload.get("memory_store_id") + self.channel_settings: Optional[Dict[str, CreateConfigurationRequestChannelSettingsValue]] = payload.get("channel_settings") + self.status_callbacks: Optional[List[ConfigurationList.CreateConfigurationRequestStatusCallbacks]] = payload.get("status_callbacks") + self.intelligence_configuration_ids: Optional[List[str]] = payload.get("intelligence_configuration_ids") + + def to_dict(self): + return { + + "display_name": self.display_name, + "description": self.description, + "conversation_grouping_type": self.conversation_grouping_type, + "memory_store_id": self.memory_store_id, + "channel_settings": [channel_settings.to_dict() for channel_settings in self.channel_settings] if self.channel_settings is not None else None, + "status_callbacks": [status_callbacks.to_dict() for status_callbacks in self.status_callbacks] if self.status_callbacks is not None else None, + "intelligence_configuration_ids": self.intelligence_configuration_ids, + } + + class CreateConfigurationRequestChannelSettingsValue(object): + """ + :ivar status_timeouts: + :ivar capture_rules: + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.status_timeouts: Optional[CreateConfigurationRequestChannelSettingsValueStatusTimeouts] = payload.get("status_timeouts") + self.capture_rules: Optional[List[CreateConfigurationRequestChannelSettingsValueCaptureRules]] = payload.get("capture_rules") + + def to_dict(self): + return { + + "": self.status_timeouts.to_dict() if self.status_timeouts is not None else None , + "": [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 { + + "": self._from, + "": self.to, + "": 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 { + + "": self.inactive, + "": 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 Maestro (Conversations) 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: + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.display_name: Optional[str] = payload.get("display_name") + self.description: Optional[str] = payload.get("description") + self.conversation_grouping_type: Optional["ConfigurationInstance.str"] = payload.get("conversation_grouping_type") + self.memory_store_id: Optional[str] = payload.get("memory_store_id") + self.channel_settings: Optional[Dict[str, UpdateConfigurationRequestChannelSettingsValue]] = payload.get("channel_settings") + self.status_callbacks: Optional[List[ConfigurationList.UpdateConfigurationRequestStatusCallbacks]] = payload.get("status_callbacks") + self.intelligence_configuration_ids: Optional[List[str]] = payload.get("intelligence_configuration_ids") + + def to_dict(self): + return { + + "display_name": self.display_name, + "description": self.description, + "conversation_grouping_type": self.conversation_grouping_type, + "memory_store_id": self.memory_store_id, + "channel_settings": [channel_settings.to_dict() for channel_settings in self.channel_settings] if self.channel_settings is not None else None, + "status_callbacks": [status_callbacks.to_dict() for status_callbacks in self.status_callbacks] if self.status_callbacks is not None else None, + "intelligence_configuration_ids": self.intelligence_configuration_ids, + } + + class UpdateConfigurationRequestChannelSettingsValue(object): + """ + :ivar status_timeouts: + :ivar capture_rules: + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.status_timeouts: Optional[UpdateConfigurationRequestChannelSettingsValueStatusTimeouts] = payload.get("status_timeouts") + self.capture_rules: Optional[List[UpdateConfigurationRequestChannelSettingsValueCaptureRules]] = payload.get("capture_rules") + + def to_dict(self): + return { + + "": self.status_timeouts.to_dict() if self.status_timeouts is not None else None , + "": [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 { + + "": self._from, + "": self.to, + "": 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 { + + "": self.inactive, + "": 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, + } + + + + """ + :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_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 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. + """ + + 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[str] = payload.get("conversationGroupingType") + self.memory_store_id: Optional[str] = payload.get("memoryStoreId") + self.channel_settings: Optional[Dict[str, str]] = payload.get("channelSettings") + self.status_callbacks: Optional[List[str]] = payload.get("statusCallbacks") + self.intelligence_configuration_ids: Optional[List[str]] = payload.get("intelligenceConfigurationIds") + 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._solution = { + "sid": sid or self.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) -> 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: Union[UpdateConfigurationRequest, object]=values.unset) -> "ConfigurationInstance": + """ + Update the ConfigurationInstance + + :param update_configuration_request: The configuration to update + + :returns: The updated ConfigurationInstance + """ + return self._proxy.update(update_configuration_request=update_configuration_request, ) + + async def update_async(self, update_configuration_request: Union[UpdateConfigurationRequest, object]=values.unset) -> "ConfigurationInstance": + """ + Asynchronous coroutine to update the ConfigurationInstance + + :param update_configuration_request: The configuration to update + + :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: Union[UpdateConfigurationRequest, object]=values.unset) -> ApiResponse: + """ + Update the ConfigurationInstance with HTTP info + + :param update_configuration_request: The configuration to update + + :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: Union[UpdateConfigurationRequest, object]=values.unset) -> ApiResponse: + """ + Asynchronous coroutine to update the ConfigurationInstance with HTTP info + + :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(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): + + 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 { + + "": self._from, + "": self.to, + "": self.metadata, + } + + 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 { + + "": self.inactive, + "": 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 Maestro (Conversations) uses to assign communications to conversations. + :ivar memory_store_id: The memory store ID that Maestro (Conversations) 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. + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.display_name: Optional[str] = payload.get("display_name") + self.description: Optional[str] = payload.get("description") + self.conversation_grouping_type: Optional["ConfigurationInstance.str"] = payload.get("conversation_grouping_type") + self.memory_store_id: Optional[str] = payload.get("memory_store_id") + self.channel_settings: Optional[Dict[str, CreateConfigurationRequestChannelSettingsValue]] = payload.get("channel_settings") + self.status_callbacks: Optional[List[ConfigurationList.CreateConfigurationRequestStatusCallbacks]] = payload.get("status_callbacks") + self.intelligence_configuration_ids: Optional[List[str]] = payload.get("intelligence_configuration_ids") + + def to_dict(self): + return { + + "display_name": self.display_name, + "description": self.description, + "conversation_grouping_type": self.conversation_grouping_type, + "memory_store_id": self.memory_store_id, + "channel_settings": [channel_settings.to_dict() for channel_settings in self.channel_settings] if self.channel_settings is not None else None, + "status_callbacks": [status_callbacks.to_dict() for status_callbacks in self.status_callbacks] if self.status_callbacks is not None else None, + "intelligence_configuration_ids": self.intelligence_configuration_ids, + } + + class CreateConfigurationRequestChannelSettingsValue(object): + """ + :ivar status_timeouts: + :ivar capture_rules: + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.status_timeouts: Optional[CreateConfigurationRequestChannelSettingsValueStatusTimeouts] = payload.get("status_timeouts") + self.capture_rules: Optional[List[CreateConfigurationRequestChannelSettingsValueCaptureRules]] = payload.get("capture_rules") + + def to_dict(self): + return { + + "": self.status_timeouts.to_dict() if self.status_timeouts is not None else None , + "": [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 { + + "": self._from, + "": self.to, + "": 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 { + + "": self.inactive, + "": 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 Maestro (Conversations) 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: + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.display_name: Optional[str] = payload.get("display_name") + self.description: Optional[str] = payload.get("description") + self.conversation_grouping_type: Optional["ConfigurationInstance.str"] = payload.get("conversation_grouping_type") + self.memory_store_id: Optional[str] = payload.get("memory_store_id") + self.channel_settings: Optional[Dict[str, UpdateConfigurationRequestChannelSettingsValue]] = payload.get("channel_settings") + self.status_callbacks: Optional[List[ConfigurationList.UpdateConfigurationRequestStatusCallbacks]] = payload.get("status_callbacks") + self.intelligence_configuration_ids: Optional[List[str]] = payload.get("intelligence_configuration_ids") + + def to_dict(self): + return { + + "display_name": self.display_name, + "description": self.description, + "conversation_grouping_type": self.conversation_grouping_type, + "memory_store_id": self.memory_store_id, + "channel_settings": [channel_settings.to_dict() for channel_settings in self.channel_settings] if self.channel_settings is not None else None, + "status_callbacks": [status_callbacks.to_dict() for status_callbacks in self.status_callbacks] if self.status_callbacks is not None else None, + "intelligence_configuration_ids": self.intelligence_configuration_ids, + } + + class UpdateConfigurationRequestChannelSettingsValue(object): + """ + :ivar status_timeouts: + :ivar capture_rules: + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.status_timeouts: Optional[UpdateConfigurationRequestChannelSettingsValueStatusTimeouts] = payload.get("status_timeouts") + self.capture_rules: Optional[List[UpdateConfigurationRequestChannelSettingsValueCaptureRules]] = payload.get("capture_rules") + + def to_dict(self): + return { + + "": self.status_timeouts.to_dict() if self.status_timeouts is not None else None , + "": [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 { + + "": self._from, + "": self.to, + "": 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 { + + "": self.inactive, + "": 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, 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) -> 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, + 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, 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({}) + + + 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: Union[UpdateConfigurationRequest, object]=values.unset) -> ConfigurationInstance: + """ + Update the ConfigurationInstance + + :param update_configuration_request: The configuration to update + + :returns: The updated ConfigurationInstance + """ + payload, _, _ = self._update(update_configuration_request=update_configuration_request) + return ConfigurationInstance( + self._version, + payload, + sid=self._solution['sid'] + ) + + def update_with_http_info(self, update_configuration_request: Union[UpdateConfigurationRequest, object]=values.unset) -> ApiResponse: + """ + Update the ConfigurationInstance and return response metadata + + :param update_configuration_request: The configuration to update + + :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, + sid=self._solution['sid'] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, 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({}) + + + 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: Union[UpdateConfigurationRequest, object]=values.unset) -> ConfigurationInstance: + """ + Asynchronous coroutine to update the ConfigurationInstance + + :param update_configuration_request: The configuration to update + + :returns: The updated ConfigurationInstance + """ + payload, _, _ = await self._update_async(update_configuration_request=update_configuration_request) + return ConfigurationInstance( + self._version, + payload, + sid=self._solution['sid'] + ) + + async def update_with_http_info_async(self, update_configuration_request: Union[UpdateConfigurationRequest, object]=values.unset) -> ApiResponse: + """ + Asynchronous coroutine to update the ConfigurationInstance and return response metadata + + :param update_configuration_request: The configuration to update + + :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, + 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 { + + "": self._from, + "": self.to, + "": self.metadata, + } + + 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 { + + "": self.inactive, + "": 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 Maestro (Conversations) uses to assign communications to conversations. + :ivar memory_store_id: The memory store ID that Maestro (Conversations) 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. + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.display_name: Optional[str] = payload.get("display_name") + self.description: Optional[str] = payload.get("description") + self.conversation_grouping_type: Optional["ConfigurationInstance.str"] = payload.get("conversation_grouping_type") + self.memory_store_id: Optional[str] = payload.get("memory_store_id") + self.channel_settings: Optional[Dict[str, CreateConfigurationRequestChannelSettingsValue]] = payload.get("channel_settings") + self.status_callbacks: Optional[List[ConfigurationList.CreateConfigurationRequestStatusCallbacks]] = payload.get("status_callbacks") + self.intelligence_configuration_ids: Optional[List[str]] = payload.get("intelligence_configuration_ids") + + def to_dict(self): + return { + + "display_name": self.display_name, + "description": self.description, + "conversation_grouping_type": self.conversation_grouping_type, + "memory_store_id": self.memory_store_id, + "channel_settings": [channel_settings.to_dict() for channel_settings in self.channel_settings] if self.channel_settings is not None else None, + "status_callbacks": [status_callbacks.to_dict() for status_callbacks in self.status_callbacks] if self.status_callbacks is not None else None, + "intelligence_configuration_ids": self.intelligence_configuration_ids, + } + + class CreateConfigurationRequestChannelSettingsValue(object): + """ + :ivar status_timeouts: + :ivar capture_rules: + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.status_timeouts: Optional[CreateConfigurationRequestChannelSettingsValueStatusTimeouts] = payload.get("status_timeouts") + self.capture_rules: Optional[List[CreateConfigurationRequestChannelSettingsValueCaptureRules]] = payload.get("capture_rules") + + def to_dict(self): + return { + + "": self.status_timeouts.to_dict() if self.status_timeouts is not None else None , + "": [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 { + + "": self._from, + "": self.to, + "": 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 { + + "": self.inactive, + "": 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 Maestro (Conversations) 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: + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.display_name: Optional[str] = payload.get("display_name") + self.description: Optional[str] = payload.get("description") + self.conversation_grouping_type: Optional["ConfigurationInstance.str"] = payload.get("conversation_grouping_type") + self.memory_store_id: Optional[str] = payload.get("memory_store_id") + self.channel_settings: Optional[Dict[str, UpdateConfigurationRequestChannelSettingsValue]] = payload.get("channel_settings") + self.status_callbacks: Optional[List[ConfigurationList.UpdateConfigurationRequestStatusCallbacks]] = payload.get("status_callbacks") + self.intelligence_configuration_ids: Optional[List[str]] = payload.get("intelligence_configuration_ids") + + def to_dict(self): + return { + + "display_name": self.display_name, + "description": self.description, + "conversation_grouping_type": self.conversation_grouping_type, + "memory_store_id": self.memory_store_id, + "channel_settings": [channel_settings.to_dict() for channel_settings in self.channel_settings] if self.channel_settings is not None else None, + "status_callbacks": [status_callbacks.to_dict() for status_callbacks in self.status_callbacks] if self.status_callbacks is not None else None, + "intelligence_configuration_ids": self.intelligence_configuration_ids, + } + + class UpdateConfigurationRequestChannelSettingsValue(object): + """ + :ivar status_timeouts: + :ivar capture_rules: + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.status_timeouts: Optional[UpdateConfigurationRequestChannelSettingsValueStatusTimeouts] = payload.get("status_timeouts") + self.capture_rules: Optional[List[UpdateConfigurationRequestChannelSettingsValueCaptureRules]] = payload.get("capture_rules") + + def to_dict(self): + return { + + "": self.status_timeouts.to_dict() if self.status_timeouts is not None else None , + "": [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 { + + "": self._from, + "": self.to, + "": 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 { + + "": self.inactive, + "": 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, 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({ + '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: Union[CreateConfigurationRequest, object]=values.unset) -> ConfigurationInstance: + """ + Create the ConfigurationInstance + + :param create_configuration_request: The configuration to create + + :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: Union[CreateConfigurationRequest, object]=values.unset) -> ApiResponse: + """ + Create the ConfigurationInstance and return response metadata + + :param create_configuration_request: The configuration to create + + :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: 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({ + '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: Union[CreateConfigurationRequest, object]=values.unset) -> ConfigurationInstance: + """ + Asynchronously create the ConfigurationInstance + + :param create_configuration_request: The configuration to create + + :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: Union[CreateConfigurationRequest, object]=values.unset) -> ApiResponse: + """ + Asynchronously create the ConfigurationInstance and return response metadata + + :param create_configuration_request: The configuration to create + + :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: 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( + 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: 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( + 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: 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( + 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: 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( + 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: 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( + 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: 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( + 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: 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( + 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: 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( + 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: 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 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: 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 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: 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 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_token: Union[str, object] = values.unset, + 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 page_token: PageToken provided by the API + :param page_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, 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 000000000..a57fddf38 --- /dev/null +++ b/twilio/rest/conversations/v2/conversation.py @@ -0,0 +1,1596 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Maestro (Conversations) + 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 datetime import date, datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator, Protocol +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 ResponseResource(Protocol): + pass + +''' +Nested response model for ConversationsV2CaptureRule +''' +class ConversationsV2CaptureRule: + def __init__(self,_from: str, to: str, metadata: Dict[str, str]): + self._from = _from + self.to = to + self.metadata = metadata + + + +''' +Nested response model for ConversationsV2ChannelSetting +''' +class ConversationsV2ChannelSetting: + def __init__(self,status_timeouts: ConversationsV2StatusTimeouts, capture_rules: List[ConversationsV2CaptureRule]): + self.status_timeouts = status_timeouts + self.capture_rules = capture_rules + + + +''' +Nested response model for ConversationsV2StatusCallbackConfig +''' +class ConversationsV2StatusCallbackConfig: + def __init__(self,url: str, method: str): + self.url = url + self.method = method + + + +''' +Nested response model for ConversationsV2StatusTimeouts +''' +class ConversationsV2StatusTimeouts: + def __init__(self,inactive: int, closed: int): + self.inactive = inactive + self.closed = closed + + + +''' +Nested response model for CreateConversationWithConfigRequest +''' +class CreateConversationWithConfigRequest: + def __init__(self,configuration_id: str, name: str): + self.configuration_id = configuration_id + self.name = name + + + +''' +Nested response model for ListConversationByAccount200ResponseConversationsConfiguration +''' +class ListConversationByAccount200ResponseConversationsConfiguration: + def __init__(self,display_name: str, description: str, conversation_grouping_type: str, memory_store_id: str, channel_settings: Dict[str, ConversationsV2ChannelSetting], status_callbacks: List[ConversationsV2StatusCallbackConfig], intelligence_configuration_ids: List[str]): + self.display_name = display_name + self.description = description + self.conversation_grouping_type = conversation_grouping_type + self.memory_store_id = memory_store_id + self.channel_settings = channel_settings + self.status_callbacks = status_callbacks + self.intelligence_configuration_ids = intelligence_configuration_ids + + + +''' +Nested response model for UpdateConversationByIdRequest +''' +class UpdateConversationByIdRequest: + def __init__(self,name: str, status: "ConversationInstance.str", configuration: ConversationList.UpdateConversationByIdRequestConfiguration): + self.name = name + self.status = status + self.configuration = configuration + + + +''' +Nested response model for UpdateConversationByIdRequestConfiguration +''' +class UpdateConversationByIdRequestConfiguration: + def __init__(self,intelligence_configuration_ids: List[str]): + self.intelligence_configuration_ids = intelligence_configuration_ids + + + + + +""" +Response model for ListConversationByAccount_200_response_conversations operations +""" +class ListConversationByAccount_200_response_conversationsResource: + def __init__(self,id: str, account_id: str, configuration_id: str, status: str, name: str, created_at: datetime, updated_at: datetime, configuration: str): + """ + Initialize the ListConversationByAccount_200_response_conversationsResource + :param id: Conversation ID. + :param account_id: Account ID. + :param configuration_id: Configuration ID. + :param status: Conversation status. + :param name: Conversation name. + :param created_at: Timestamp when this Conversation was created. + :param updated_at: Timestamp when this Conversation was last updated. + :param configuration: + + """ + self.id = id + self.account_id = account_id + self.configuration_id = configuration_id + self.status = status + self.name = name + self.created_at = created_at + self.updated_at = updated_at + self.configuration = configuration + + +""" +Response model for ListConfiguration_400_response operations +""" +class ListConfiguration_400_responseResource: + def __init__(self,code: int, message: str, more_info: str, status: int): + """ + Initialize the ListConfiguration_400_responseResource + :param code: Twilio-specific error code + :param message: Error message + :param more_info: Link to Error Code References + :param status: HTTP response status code + + """ + self.code = code + self.message = message + self.more_info = more_info + self.status = status + + + + +class ConversationInstance(InstanceResource): + + 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 { + + "": self._from, + "": self.to, + "": self.metadata, + } + + 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 { + + "": self.inactive, + "": self.closed, + } + + class CreateConversationWithConfigRequest(object): + """ + :ivar configuration_id: The ID of an existing configuration. + :ivar name: The name of the conversation. + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.configuration_id: Optional[str] = payload.get("configuration_id") + self.name: Optional[str] = payload.get("name") + + def to_dict(self): + return { + + "configuration_id": self.configuration_id, + "name": self.name, + } + + class UpdateConversationByIdRequest(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.UpdateConversationByIdRequestConfiguration] = 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 UpdateConversationByIdRequestConfiguration(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("intelligence_configuration_ids") + + def to_dict(self): + return { + + "intelligence_configuration_ids": self.intelligence_configuration_ids, + } + + + + """ + :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: + """ + + 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[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._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ConversationContext] = None + + @property + def _proxy(self) -> "ConversationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ConversationContext for this ConversationInstance + """ + if self._context is None: + self._context = ConversationContext(self._version, sid=self._solution['sid'],) + return self._context + + + def delete(self) -> bool: + """ + Deletes the ConversationInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ConversationInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ConversationInstance 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 ConversationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + + 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, 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): + + 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 { + + "": self._from, + "": self.to, + "": self.metadata, + } + + 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 { + + "": self.inactive, + "": self.closed, + } + + class CreateConversationWithConfigRequest(object): + """ + :ivar configuration_id: The ID of an existing configuration. + :ivar name: The name of the conversation. + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.configuration_id: Optional[str] = payload.get("configuration_id") + self.name: Optional[str] = payload.get("name") + + def to_dict(self): + return { + + "configuration_id": self.configuration_id, + "name": self.name, + } + + class UpdateConversationByIdRequest(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.UpdateConversationByIdRequestConfiguration] = 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 UpdateConversationByIdRequestConfiguration(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("intelligence_configuration_ids") + + def to_dict(self): + return { + + "intelligence_configuration_ids": self.intelligence_configuration_ids, + } + + + 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) -> 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 ConversationInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ConversationInstance 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 ConversationInstance + + + :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 ConversationInstance 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) -> 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 _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 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 { + + "": self._from, + "": self.to, + "": self.metadata, + } + + 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 { + + "": self.inactive, + "": self.closed, + } + + class CreateConversationWithConfigRequest(object): + """ + :ivar configuration_id: The ID of an existing configuration. + :ivar name: The name of the conversation. + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.configuration_id: Optional[str] = payload.get("configuration_id") + self.name: Optional[str] = payload.get("name") + + def to_dict(self): + return { + + "configuration_id": self.configuration_id, + "name": self.name, + } + + class UpdateConversationByIdRequest(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.UpdateConversationByIdRequestConfiguration] = 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 UpdateConversationByIdRequestConfiguration(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("intelligence_configuration_ids") + + def to_dict(self): + return { + + "intelligence_configuration_ids": self.intelligence_configuration_ids, + } + + + 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, + addresses: Union[List[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 List[str] addresses: Filter Conversations by Participant addresses. Requires at least 2 addresses. Returns Conversations across all channels for the specified address pair. Must be URL-encoded ('+' becomes '%2B', '@' becomes '%40'). + :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, + addresses=addresses, + 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, + addresses: Union[List[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 List[str] addresses: Filter Conversations by Participant addresses. Requires at least 2 addresses. Returns Conversations across all channels for the specified address pair. Must be URL-encoded ('+' becomes '%2B', '@' becomes '%40'). + :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, + addresses=addresses, + 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, + addresses: Union[List[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 List[str] addresses: Filter Conversations by Participant addresses. Requires at least 2 addresses. Returns Conversations across all channels for the specified address pair. Must be URL-encoded ('+' becomes '%2B', '@' becomes '%40'). + :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, + addresses=addresses, + 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, + addresses: Union[List[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 List[str] addresses: Filter Conversations by Participant addresses. Requires at least 2 addresses. Returns Conversations across all channels for the specified address pair. Must be URL-encoded ('+' becomes '%2B', '@' becomes '%40'). + :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, + addresses=addresses, + 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, + addresses: Union[List[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 List[str] addresses: Filter Conversations by Participant addresses. Requires at least 2 addresses. Returns Conversations across all channels for the specified address pair. Must be URL-encoded ('+' becomes '%2B', '@' becomes '%40'). + :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, + addresses=addresses, + 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, + addresses: Union[List[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 List[str] addresses: Filter Conversations by Participant addresses. Requires at least 2 addresses. Returns Conversations across all channels for the specified address pair. Must be URL-encoded ('+' becomes '%2B', '@' becomes '%40'). + :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, + addresses=addresses, + 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, + addresses: Union[List[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 List[str] addresses: Filter Conversations by Participant addresses. Requires at least 2 addresses. Returns Conversations across all channels for the specified address pair. Must be URL-encoded ('+' becomes '%2B', '@' becomes '%40'). + :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, + addresses=addresses, + 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, + addresses: Union[List[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 List[str] addresses: Filter Conversations by Participant addresses. Requires at least 2 addresses. Returns Conversations across all channels for the specified address pair. Must be URL-encoded ('+' becomes '%2B', '@' becomes '%40'). + :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, + addresses=addresses, + 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, + addresses: Union[List[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 addresses: Filter Conversations by Participant addresses. Requires at least 2 addresses. Returns Conversations across all channels for the specified address pair. Must be URL-encoded ('+' becomes '%2B', '@' becomes '%40'). + :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, + 'addresses': serialize.map(addresses, lambda e: e), + '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, + addresses: Union[List[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 addresses: Filter Conversations by Participant addresses. Requires at least 2 addresses. Returns Conversations across all channels for the specified address pair. Must be URL-encoded ('+' becomes '%2B', '@' becomes '%40'). + :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, + 'addresses': serialize.map(addresses, lambda e: e), + '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, + addresses: 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 status: Filters for specific statuses + :param channel_id: The resource identifier (such as callSid or messageSid) to filter conversations. + :param addresses: Filter Conversations by Participant addresses. Requires at least 2 addresses. Returns Conversations across all channels for the specified address pair. Must be URL-encoded ('+' becomes '%2B', '@' becomes '%40'). + :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, + 'addresses': serialize.map(addresses, lambda e: e), + '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, + addresses: Union[List[str], object] = values.unset, + + page_token: Union[str, object] = 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 addresses: Filter Conversations by Participant addresses. Requires at least 2 addresses. Returns Conversations across all channels for the specified address pair. Must be URL-encoded ('+' becomes '%2B', '@' becomes '%40'). + :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, + 'addresses': serialize.map(addresses, lambda e: e), + '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/participant.py b/twilio/rest/conversations/v2/participant.py new file mode 100644 index 000000000..15da050a7 --- /dev/null +++ b/twilio/rest/conversations/v2/participant.py @@ -0,0 +1,1101 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Maestro (Conversations) + 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 datetime import date, datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator, Protocol +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 ParticipantInstance(InstanceResource): + + 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("profile_id") + self.addresses: Optional[List[ParticipantList.CreateParticipantInConversationRequestAddresses]] = payload.get("addresses") + + def to_dict(self): + return { + + "name": self.name, + "type": self.type, + "profile_id": 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("channel_id") + + def to_dict(self): + return { + + "channel": self.channel, + "address": self.address, + "channel_id": self.channel_id, + } + + + + """ + :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: Optional[str] = None, 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[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")) + + + self._solution = { + "conversation_sid": conversation_sid or self.conversation_sid, + "sid": sid or self.sid, + } + self._context: Optional[ParticipantContext] = None + + @property + def _proxy(self) -> "ParticipantContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ParticipantContext for this ParticipantInstance + """ + if self._context is None: + self._context = ParticipantContext(self._version, conversation_sid=self._solution['conversation_sid'], sid=self._solution['sid'],) + return self._context + + + def 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, create_participant_in_conversation_request: Union[CreateParticipantInConversationRequest, object]=values.unset) -> "ParticipantInstance": + """ + Update the ParticipantInstance + + :param create_participant_in_conversation_request: + + :returns: The updated ParticipantInstance + """ + return self._proxy.update(create_participant_in_conversation_request=create_participant_in_conversation_request, ) + + async def update_async(self, create_participant_in_conversation_request: Union[CreateParticipantInConversationRequest, object]=values.unset) -> "ParticipantInstance": + """ + Asynchronous coroutine to update the ParticipantInstance + + :param create_participant_in_conversation_request: + + :returns: The updated ParticipantInstance + """ + return await self._proxy.update_async(create_participant_in_conversation_request=create_participant_in_conversation_request, ) + + def update_with_http_info(self, create_participant_in_conversation_request: Union[CreateParticipantInConversationRequest, object]=values.unset) -> ApiResponse: + """ + Update the ParticipantInstance with HTTP info + + :param create_participant_in_conversation_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info(create_participant_in_conversation_request=create_participant_in_conversation_request, ) + + async def update_with_http_info_async(self, create_participant_in_conversation_request: Union[CreateParticipantInConversationRequest, object]=values.unset) -> ApiResponse: + """ + Asynchronous coroutine to update the ParticipantInstance with HTTP info + + :param create_participant_in_conversation_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async(create_participant_in_conversation_request=create_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): + + 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("profile_id") + self.addresses: Optional[List[ParticipantList.CreateParticipantInConversationRequestAddresses]] = payload.get("addresses") + + def to_dict(self): + return { + + "name": self.name, + "type": self.type, + "profile_id": 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("channel_id") + + def to_dict(self): + return { + + "channel": self.channel, + "address": self.address, + "channel_id": self.channel_id, + } + + + 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, create_participant_in_conversation_request: Union[CreateParticipantInConversationRequest, object]=values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_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, create_participant_in_conversation_request: Union[CreateParticipantInConversationRequest, object]=values.unset) -> ParticipantInstance: + """ + Update the ParticipantInstance + + :param create_participant_in_conversation_request: + + :returns: The updated ParticipantInstance + """ + payload, _, _ = self._update(create_participant_in_conversation_request=create_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, create_participant_in_conversation_request: Union[CreateParticipantInConversationRequest, object]=values.unset) -> ApiResponse: + """ + Update 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._update(create_participant_in_conversation_request=create_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, create_participant_in_conversation_request: Union[CreateParticipantInConversationRequest, object]=values.unset) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_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, create_participant_in_conversation_request: Union[CreateParticipantInConversationRequest, object]=values.unset) -> ParticipantInstance: + """ + Asynchronous coroutine to update the ParticipantInstance + + :param create_participant_in_conversation_request: + + :returns: The updated ParticipantInstance + """ + payload, _, _ = await self._update_async(create_participant_in_conversation_request=create_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, create_participant_in_conversation_request: Union[CreateParticipantInConversationRequest, object]=values.unset) -> ApiResponse: + """ + Asynchronous coroutine to update 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._update_async(create_participant_in_conversation_request=create_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("profile_id") + self.addresses: Optional[List[ParticipantList.CreateParticipantInConversationRequestAddresses]] = payload.get("addresses") + + def to_dict(self): + return { + + "name": self.name, + "type": self.type, + "profile_id": 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("channel_id") + + def to_dict(self): + return { + + "channel": self.channel, + "address": self.address, + "channel_id": self.channel_id, + } + + + 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, 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, 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, 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_token: Union[str, object] = values.unset, + 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, 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, self._solution) + + async def get_page_async(self, target_url: str) -> ParticipantPage: + """ + Asynchronously retrieve a specific page of ParticipantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantInstance + """ + response = await self._version.domain.twilio.request_async( + 'GET', + target_url + ) + return ParticipantPage(self._version, response, self._solution) + + + + def get(self, conversation_sid: str, sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param conversation_sid: + :param sid: + """ + return ParticipantContext(self._version, conversation_sid=conversation_sid, sid=sid) + + def __call__(self, conversation_sid: str, sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param conversation_sid: + :param sid: + """ + return ParticipantContext(self._version, conversation_sid=conversation_sid, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return '' + diff --git a/twilio/rest/memory/v1/__init__.py b/twilio/rest/memory/v1/__init__.py new file mode 100644 index 000000000..dd014df8a --- /dev/null +++ b/twilio/rest/memory/v1/__init__.py @@ -0,0 +1,147 @@ +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.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.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._bulk: Optional[BulkList] = None + self._conversation_summaries: Optional[ConversationSummaryList] = None + self._events: Optional[EventList] = None + self._identifiers: Optional[IdentifierList] = None + self._identity_resolution_settings: Optional[IdentityResolutionSettingList] = None + self._import_: Optional[ImportList] = None + self._lookup: Optional[LookupList] = None + self._observations: Optional[ObservationList] = None + self._profiles: Optional[ProfileList] = None + self._recall: Optional[RecallList] = None + self._revisions: Optional[RevisionList] = None + self._stores: Optional[StoreList] = None + self._traits: Optional[TraitList] = None + self._trait_groups: Optional[TraitGroupList] = None + + @property + def bulk(self) -> BulkList: + if self._bulk is None: + self._bulk = BulkList(self) + return self._bulk + + @property + def conversation_summaries(self) -> ConversationSummaryList: + if self._conversation_summaries is None: + self._conversation_summaries = ConversationSummaryList(self) + return self._conversation_summaries + + @property + def events(self) -> EventList: + if self._events is None: + self._events = EventList(self) + return self._events + + @property + def identifiers(self) -> IdentifierList: + if self._identifiers is None: + self._identifiers = IdentifierList(self) + return self._identifiers + + @property + def identity_resolution_settings(self) -> IdentityResolutionSettingList: + if self._identity_resolution_settings is None: + self._identity_resolution_settings = IdentityResolutionSettingList(self) + return self._identity_resolution_settings + + @property + def import_(self) -> ImportList: + if self._import_ is None: + self._import_ = ImportList(self) + return self._import_ + + @property + def lookup(self) -> LookupList: + if self._lookup is None: + self._lookup = LookupList(self) + return self._lookup + + @property + def observations(self) -> ObservationList: + if self._observations is None: + self._observations = ObservationList(self) + return self._observations + + @property + def profiles(self) -> ProfileList: + if self._profiles is None: + self._profiles = ProfileList(self) + return self._profiles + + @property + def recall(self) -> RecallList: + if self._recall is None: + self._recall = RecallList(self) + return self._recall + + @property + def revisions(self) -> RevisionList: + if self._revisions is None: + self._revisions = RevisionList(self) + return self._revisions + + @property + def stores(self) -> StoreList: + if self._stores is None: + self._stores = StoreList(self) + return self._stores + + @property + def traits(self) -> TraitList: + if self._traits is None: + self._traits = TraitList(self) + return self._traits + + @property + def trait_groups(self) -> TraitGroupList: + if self._trait_groups is None: + self._trait_groups = TraitGroupList(self) + return self._trait_groups + + 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 000000000..0d01c323a --- /dev/null +++ b/twilio/rest/memory/v1/bulk.py @@ -0,0 +1,381 @@ +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 datetime import date, datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator, Protocol +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 BulkInstance(InstanceResource): + + 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, + } + + + + """ + :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") + + + self._solution = { + "store_id": store_id or self.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): + + 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, 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 000000000..65438277d --- /dev/null +++ b/twilio/rest/memory/v1/conversation_summary.py @@ -0,0 +1,661 @@ +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 datetime import date, datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator, Protocol +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 ResponseResource(Protocol): + pass + +''' +Nested response model for CreateSummariesRequest +''' +class CreateSummariesRequest: + def __init__(self,summaries: List[ConversationSummaryList.SummaryCore]): + self.summaries = summaries + + + +''' +Nested response model for SummaryCore +''' +class SummaryCore: + def __init__(self,source: str, content: str, occurred_at: datetime, conversation_id: str): + self.source = source + self.content = content + self.occurred_at = occurred_at + self.conversation_id = conversation_id + + + + + +""" +Response model for DeleteProfileConversationSummary_202_response operations +""" +class DeleteProfileConversationSummary_202_responseResource: + def __init__(self,message: str): + """ + Initialize the DeleteProfileConversationSummary_202_responseResource + :param message: + + """ + self.message = message + + +""" +Response model for SummaryInfo operations +""" +class SummaryInfoResource: + def __init__(self,source: str, content: str, occurred_at: datetime, conversation_id: str, id: str, created_at: datetime, updated_at: datetime): + """ + Initialize the SummaryInfoResource + :param 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. + :param content: The main content of the summary. + :param occurred_at: The timestamp when the summary was originally created. + :param conversation_id: A unique identifier for the conversation using Twilio Type ID (TTID) format. + :param id: A unique identifier for the summary using Twilio Type ID (TTID) format. + :param created_at: The timestamp when the summary was created. + :param updated_at: The timestamp when the summary was last updated. + + """ + self.source = source + self.content = content + self.occurred_at = occurred_at + self.conversation_id = conversation_id + self.id = id + self.created_at = created_at + self.updated_at = updated_at + + +""" +Response model for SummariesCreatedResponse operations +""" +class SummariesCreatedResponseResource: + def __init__(self,message: str): + """ + Initialize the SummariesCreatedResponseResource + :param message: Confirmation message for the operation. + + """ + self.message = message + + + + +class ConversationSummaryInstance(InstanceResource): + + 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("occurred_at") + self.conversation_id: Optional[str] = payload.get("conversation_id") + + def to_dict(self): + return { + + "source": self.source, + "content": self.content, + "occurred_at": self.occurred_at, + "conversation_id": self.conversation_id, + } + + + + """ + :ivar message: Confirmation message for the operation. + """ + + def __init__(self, version: Version, payload:ResponseResource, store_id: Optional[str] = None, profile_id: Optional[str] = None): + super().__init__(version) + + + self.message: Optional[str] = payload.get("message") + + + self._solution = { + "store_id": store_id or self.store_id, + "profile_id": profile_id or self.profile_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'],) + return self._context + + + 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 + """ + return self._proxy.create(create_summaries_request, accept_encoding=accept_encoding, content_encoding=content_encoding, ) + async def create_async(self, create_summaries_request: CreateSummariesRequest, accept_encoding: Union[str, object]=values.unset, content_encoding: Union[str, object]=values.unset) -> "ConversationSummaryInstance": + """ + Asynchronous coroutine to 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 + """ + return await self._proxy.create_async(create_summaries_request, accept_encoding=accept_encoding, content_encoding=content_encoding, ) + + 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 with HTTP info + + :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 + """ + return self._proxy.create_with_http_info(create_summaries_request, accept_encoding=accept_encoding, content_encoding=content_encoding, ) + + 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: + """ + Asynchronous coroutine to create the ConversationSummaryInstance with HTTP info + + :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 + """ + return await self._proxy.create_with_http_info_async(create_summaries_request, accept_encoding=accept_encoding, content_encoding=content_encoding, ) + + + 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 __repr__(self) -> str: + """ + 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): + + 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("occurred_at") + self.conversation_id: Optional[str] = payload.get("conversation_id") + + def to_dict(self): + return { + + "source": self.source, + "content": self.content, + "occurred_at": self.occurred_at, + "conversation_id": self.conversation_id, + } + + + def __init__(self, version: Version, store_id: str, profile_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. + """ + 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({}) + + + if not (accept_encoding is values.unset or (isinstance(accept_encoding, str) and not accept_encoding)): + headers['Accept-Encoding'] = accept_encoding + + if not (content_encoding is values.unset or (isinstance(content_encoding, str) and not content_encoding)): + headers['Content-Encoding'] = content_encoding + + 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({}) + + + if not (accept_encoding is values.unset or (isinstance(accept_encoding, str) and not accept_encoding)): + headers['Accept-Encoding'] = accept_encoding + + if not (content_encoding is values.unset or (isinstance(content_encoding, str) and not content_encoding)): + headers['Content-Encoding'] = content_encoding + + 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: + """ + Asynchronous coroutine to 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: + """ + Asynchronous coroutine to 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 _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 __repr__(self) -> str: + """ + 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) + + 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("occurred_at") + self.conversation_id: Optional[str] = payload.get("conversation_id") + + def to_dict(self): + return { + + "source": self.source, + "content": self.content, + "occurred_at": self.occurred_at, + "conversation_id": self.conversation_id, + } + + + def __init__(self, version: Version): + """ + Initialize the ConversationSummaryList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + + + + + + def get(self, store_id: str, profile_id: str) -> ConversationSummaryContext: + """ + Constructs a ConversationSummaryContext + + :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. + """ + return ConversationSummaryContext(self._version, store_id=store_id, profile_id=profile_id) + + def __call__(self, store_id: str, profile_id: str) -> ConversationSummaryContext: + """ + Constructs a ConversationSummaryContext + + :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. + """ + return ConversationSummaryContext(self._version, store_id=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/event.py b/twilio/rest/memory/v1/event.py new file mode 100644 index 000000000..aa8aeb60c --- /dev/null +++ b/twilio/rest/memory/v1/event.py @@ -0,0 +1,602 @@ +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 datetime import date, datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator, Protocol +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 EventInstance(InstanceResource): + + 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("participant_id") + + def to_dict(self): + return { + + "address": self.address, + "participant_id": 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("participant_id") + + def to_dict(self): + return { + + "address": self.address, + "participant_id": 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("conversation_id") + self.communication_id: Optional[str] = payload.get("communication_id") + self.communication_type: Optional[str] = payload.get("communication_type") + self.communication_status: Optional[str] = payload.get("communication_status") + 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("error_code") + self.error_message: Optional[str] = payload.get("error_message") + + def to_dict(self): + return { + + "timestamp": self.timestamp, + "lifecycle": self.lifecycle, + "conversation_id": self.conversation_id, + "communication_id": self.communication_id, + "communication_type": self.communication_type, + "communication_status": 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 , + "error_code": self.error_code, + "error_message": self.error_message, + } + + + + """ + :ivar message: + """ + + def __init__(self, version: Version, payload:Dict[str, Any], store_id: Optional[str] = None, profile_id: Optional[str] = None): + super().__init__(version) + + + self.message: Optional[str] = payload.get("message") + + + self._solution = { + "store_id": store_id or self.store_id, + "profile_id": profile_id or self.profile_id, + } + self._context: Optional[EventContext] = None + + @property + def _proxy(self) -> "EventContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: EventContext for this EventInstance + """ + if self._context is None: + self._context = EventContext(self._version, store_id=self._solution['store_id'], profile_id=self._solution['profile_id'],) + return self._context + + + def create(self, profile_event_request: Union[ProfileEventRequest, object]=values.unset) -> "EventInstance": + """ + Create the EventInstance + + :param profile_event_request: + + :returns: The created EventInstance + """ + return self._proxy.create(profile_event_request=profile_event_request, ) + async def create_async(self, profile_event_request: Union[ProfileEventRequest, object]=values.unset) -> "EventInstance": + """ + Asynchronous coroutine to create the EventInstance + + :param profile_event_request: + + :returns: The created EventInstance + """ + return await self._proxy.create_async(profile_event_request=profile_event_request, ) + + def create_with_http_info(self, profile_event_request: Union[ProfileEventRequest, object]=values.unset) -> ApiResponse: + """ + Create the EventInstance with HTTP info + + :param profile_event_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info(profile_event_request=profile_event_request, ) + + async def create_with_http_info_async(self, profile_event_request: Union[ProfileEventRequest, object]=values.unset) -> ApiResponse: + """ + Asynchronous coroutine to create the EventInstance with HTTP info + + :param profile_event_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_async(profile_event_request=profile_event_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 EventContext(InstanceContext): + + 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("participant_id") + + def to_dict(self): + return { + + "address": self.address, + "participant_id": 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("participant_id") + + def to_dict(self): + return { + + "address": self.address, + "participant_id": 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("conversation_id") + self.communication_id: Optional[str] = payload.get("communication_id") + self.communication_type: Optional[str] = payload.get("communication_type") + self.communication_status: Optional[str] = payload.get("communication_status") + 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("error_code") + self.error_message: Optional[str] = payload.get("error_message") + + def to_dict(self): + return { + + "timestamp": self.timestamp, + "lifecycle": self.lifecycle, + "conversation_id": self.conversation_id, + "communication_id": self.communication_id, + "communication_type": self.communication_type, + "communication_status": 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 , + "error_code": self.error_code, + "error_message": self.error_message, + } + + + def __init__(self, version: Version, store_id: str, profile_id: str): + """ + Initialize the EventContext + + :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({}) + + + 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({}) + + + 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: + """ + Asynchronous coroutine to 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: + """ + Asynchronous coroutine to 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 + """ + 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("participant_id") + + def to_dict(self): + return { + + "address": self.address, + "participant_id": 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("participant_id") + + def to_dict(self): + return { + + "address": self.address, + "participant_id": 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("conversation_id") + self.communication_id: Optional[str] = payload.get("communication_id") + self.communication_type: Optional[str] = payload.get("communication_type") + self.communication_status: Optional[str] = payload.get("communication_status") + 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("error_code") + self.error_message: Optional[str] = payload.get("error_message") + + def to_dict(self): + return { + + "timestamp": self.timestamp, + "lifecycle": self.lifecycle, + "conversation_id": self.conversation_id, + "communication_id": self.communication_id, + "communication_type": self.communication_type, + "communication_status": 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 , + "error_code": self.error_code, + "error_message": self.error_message, + } + + + def __init__(self, version: Version): + """ + Initialize the EventList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + + + + + + def get(self, store_id: str, profile_id: str) -> EventContext: + """ + Constructs a EventContext + + :param store_id: The storeId identifier + :param profile_id: The profileId identifier + """ + return EventContext(self._version, store_id=store_id, profile_id=profile_id) + + def __call__(self, store_id: str, profile_id: str) -> EventContext: + """ + Constructs a EventContext + + :param store_id: The storeId identifier + :param profile_id: The profileId identifier + """ + return EventContext(self._version, store_id=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/identifier.py b/twilio/rest/memory/v1/identifier.py new file mode 100644 index 000000000..118c4377e --- /dev/null +++ b/twilio/rest/memory/v1/identifier.py @@ -0,0 +1,961 @@ +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 datetime import date, datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator, Protocol +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 ResponseResource(Protocol): + pass + +''' +Nested response model for Identifier +''' +class Identifier: + def __init__(self,id_type: str, value: str): + self.id_type = id_type + self.value = value + + + +''' +Nested response model for IdentifierUpdate +''' +class IdentifierUpdate: + def __init__(self,id_type: str, old_value: str, new_value: str): + self.id_type = id_type + self.old_value = old_value + self.new_value = new_value + + + + + +""" +Response model for CreateProfileIdentifier_202_response operations +""" +class CreateProfileIdentifier_202_responseResource: + def __init__(self,message: str): + """ + Initialize the CreateProfileIdentifier_202_responseResource + :param message: + + """ + self.message = message + + +""" +Response model for UpdateProfileIdentifier_202_response operations +""" +class UpdateProfileIdentifier_202_responseResource: + def __init__(self,message: str): + """ + Initialize the UpdateProfileIdentifier_202_responseResource + :param message: + + """ + self.message = message + + +""" +Response model for DeleteProfileIdentifier_202_response operations +""" +class DeleteProfileIdentifier_202_responseResource: + def __init__(self,message: str): + """ + Initialize the DeleteProfileIdentifier_202_responseResource + :param message: + + """ + self.message = message + + +""" +Response model for IdentifierSet operations +""" +class IdentifierSetResource: + def __init__(self,id_type: str, values: List[str]): + """ + Initialize the IdentifierSetResource + :param id_type: Identifier type defined in Identity Resolution Settings. + :param values: Server managed collection of stored values for the identifier type. Identifier values are normalized according to the corresponding identifier settings and ordered chronologically. + + """ + self.id_type = id_type + self.values = values + + + + +class IdentifierInstance(InstanceResource): + + class Identifier(object): + """ + :ivar id_type: Identifier type as configured in the service's Identity Resolution Settings. Must match an `idType` defined in the corresponding identifier settings and must satisfy the same length constraints. + :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("id_type") + self.value: Optional[str] = payload.get("value") + + def to_dict(self): + return { + + "id_type": 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("id_type") + self.old_value: Optional[str] = payload.get("old_value") + self.new_value: Optional[str] = payload.get("new_value") + + def to_dict(self): + return { + + "id_type": self.id_type, + "old_value": self.old_value, + "new_value": self.new_value, + } + + + + """ + :ivar message: + """ + + def __init__(self, version: Version, payload:ResponseResource, store_id: Optional[str] = None, profile_id: Optional[str] = None, id_type: Optional[str] = None): + super().__init__(version) + + + self.message: Optional[str] = payload.get("message") + + + self._solution = { + "store_id": store_id or self.store_id, + "profile_id": profile_id or self.profile_id, + "id_type": id_type or self.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 create(self, identifier: Identifier) -> "IdentifierInstance": + """ + Create the IdentifierInstance + + :param identifier: + + :returns: The created IdentifierInstance + """ + return self._proxy.create(identifier, ) + async def create_async(self, identifier: Identifier) -> "IdentifierInstance": + """ + Asynchronous coroutine to create the IdentifierInstance + + :param identifier: + + :returns: The created IdentifierInstance + """ + return await self._proxy.create_async(identifier, ) + + def create_with_http_info(self, identifier: Identifier) -> ApiResponse: + """ + Create the IdentifierInstance with HTTP info + + :param identifier: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info(identifier, ) + + async def create_with_http_info_async(self, identifier: Identifier) -> ApiResponse: + """ + Asynchronous coroutine to create the IdentifierInstance with HTTP info + + :param identifier: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_async(identifier, ) + + + 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 update(self, identifier_update: IdentifierUpdate) -> "IdentifierInstance": + """ + Update the IdentifierInstance + + :param identifier_update: + + :returns: The updated IdentifierInstance + """ + return self._proxy.update(identifier_update=identifier_update, ) + + async def update_async(self, identifier_update: IdentifierUpdate) -> "IdentifierInstance": + """ + Asynchronous coroutine to update the IdentifierInstance + + :param identifier_update: + + :returns: The updated IdentifierInstance + """ + return await self._proxy.update_async(identifier_update=identifier_update, ) + + def update_with_http_info(self, identifier_update: IdentifierUpdate) -> ApiResponse: + """ + Update the IdentifierInstance with HTTP info + + :param identifier_update: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info(identifier_update=identifier_update, ) + + async def update_with_http_info_async(self, identifier_update: IdentifierUpdate) -> ApiResponse: + """ + Asynchronous coroutine to update the IdentifierInstance with HTTP info + + :param identifier_update: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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): + + class Identifier(object): + """ + :ivar id_type: Identifier type as configured in the service's Identity Resolution Settings. Must match an `idType` defined in the corresponding identifier settings and must satisfy the same length constraints. + :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("id_type") + self.value: Optional[str] = payload.get("value") + + def to_dict(self): + return { + + "id_type": 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("id_type") + self.old_value: Optional[str] = payload.get("old_value") + self.new_value: Optional[str] = payload.get("new_value") + + def to_dict(self): + return { + + "id_type": self.id_type, + "old_value": self.old_value, + "new_value": self.new_value, + } + + + 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 _create(self, identifier: Identifier) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = identifier.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, 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'], + id_type=self._solution['id_type'] + ) + + 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'], + id_type=self._solution['id_type'] + ) + 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({}) + + + 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: + """ + Asynchronous coroutine to 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'], + id_type=self._solution['id_type'] + ) + + async def create_with_http_info_async(self, identifier: Identifier) -> ApiResponse: + """ + Asynchronous coroutine to 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'], + id_type=self._solution['id_type'] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + + 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 _update(self, identifier_update: IdentifierUpdate) -> tuple: + """ + Internal helper for update 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.update_with_response_info(method='PATCH', uri=self._uri, data=data, headers=headers) + + def update(self, identifier_update: IdentifierUpdate) -> IdentifierInstance: + """ + Update the IdentifierInstance + + :param identifier_update: + + :returns: The updated IdentifierInstance + """ + payload, _, _ = self._update(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 update_with_http_info(self, identifier_update: IdentifierUpdate) -> ApiResponse: + """ + Update the IdentifierInstance and return response metadata + + :param identifier_update: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(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 _update_async(self, identifier_update: IdentifierUpdate) -> tuple: + """ + Internal async helper for update 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.update_with_response_info_async(method='PATCH', uri=self._uri, data=data, headers=headers) + + async def update_async(self, identifier_update: IdentifierUpdate) -> IdentifierInstance: + """ + Asynchronous coroutine to update the IdentifierInstance + + :param identifier_update: + + :returns: The updated IdentifierInstance + """ + payload, _, _ = await self._update_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 update_with_http_info_async(self, identifier_update: IdentifierUpdate) -> ApiResponse: + """ + Asynchronous coroutine to update the IdentifierInstance and return response metadata + + :param identifier_update: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_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) + + 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. Must match an `idType` defined in the corresponding identifier settings and must satisfy the same length constraints. + :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("id_type") + self.value: Optional[str] = payload.get("value") + + def to_dict(self): + return { + + "id_type": 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("id_type") + self.old_value: Optional[str] = payload.get("old_value") + self.new_value: Optional[str] = payload.get("new_value") + + def to_dict(self): + return { + + "id_type": self.id_type, + "old_value": self.old_value, + "new_value": self.new_value, + } + + + def __init__(self, version: Version): + """ + Initialize the IdentifierList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + + + + + + def get(self, store_id: str, profile_id: str, id_type: str) -> IdentifierContext: + """ + Constructs a IdentifierContext + + :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`). + """ + return IdentifierContext(self._version, store_id=store_id, profile_id=profile_id, id_type=id_type) + + def __call__(self, store_id: str, profile_id: str, id_type: str) -> IdentifierContext: + """ + Constructs a IdentifierContext + + :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`). + """ + return IdentifierContext(self._version, store_id=store_id, profile_id=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 000000000..83687f1ba --- /dev/null +++ b/twilio/rest/memory/v1/identity_resolution_setting.py @@ -0,0 +1,612 @@ +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 datetime import date, datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator, Protocol +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 IdentityResolutionSettingInstance(InstanceResource): + + class IdentifierConfig(object): + """ + :ivar id_type: Name of the identifier to use for identity resolution. Usual values are email, phone, user_id etc. + :ivar matching_algo: The algorithm to use for matching the identifier's value. Possible value are exact or fuzzy Exact will match the identifier exactly, while fuzzy (low precision) will allow for some variations. + :ivar matching_threshold: The threshold as percentage to use for fuzzy matching. A value between 50 and 99. Required for fuzzy algo. + :ivar limit: Maximum number of value to retain for this identifier for a profile. + :ivar limit_policy: Policy to apply when the number of values for the identifier exceeds the limit. The extra values will be removed using either fifo or lifo policy to make them compliant. fifo/lifo will be applied based on the event timestamp of the request that added the identifier. + :ivar enforce_unique: True means only one profile will have the identifier, forcing profiles that share it to merge. False would allow multiple profiles to share the identifier and only merge if there is a matching MatchingRule. + :ivar normalization: Normalization to apply to the identifier value before storing and matching. + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.id_type: Optional[str] = payload.get("id_type") + self.matching_algo: Optional["IdentityResolutionSettingInstance.str"] = payload.get("matching_algo") + self.matching_threshold: Optional[int] = payload.get("matching_threshold") + self.limit: Optional[int] = payload.get("limit") + self.limit_policy: Optional["IdentityResolutionSettingInstance.str"] = payload.get("limit_policy") + self.enforce_unique: Optional[bool] = payload.get("enforce_unique") + self.normalization: Optional["IdentityResolutionSettingInstance.str"] = payload.get("normalization") + + def to_dict(self): + return { + + "id_type": self.id_type, + "matching_algo": self.matching_algo, + "matching_threshold": self.matching_threshold, + "limit": self.limit, + "limit_policy": self.limit_policy, + "enforce_unique": self.enforce_unique, + "normalization": self.normalization, + } + + class IdentityResolutionSettingsCore(object): + """ + :ivar identifier_configs: List of identifier, traits to use as identifiers for identity resolution. + :ivar matching_rules: List of rules to apply to match identifiers for new profile updates against existing profiles (if any). Rules are evaluated in the exact order specified in this array - the identity resolution algorithm will apply rules sequentially from first to last, and this order is preserved. 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 updated with the new data. If a rule matches to multiple existing profiles, those existing profiles will be merged into a single unique profile updated with the new data. All identifiers should match based on the matching condition (e.g. matchingAlgo) as per the identifierConfigs. + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.identifier_configs: Optional[List[IdentityResolutionSettingList.IdentifierConfig]] = payload.get("identifier_configs") + self.matching_rules: Optional[List[str]] = payload.get("matching_rules") + + def to_dict(self): + return { + + "identifier_configs": [identifier_configs.to_dict() for identifier_configs in self.identifier_configs] if self.identifier_configs is not None else None, + "matching_rules": self.matching_rules, + } + + + + """ + :ivar identifier_configs: List of identifier, traits to use as identifiers for identity resolution. + :ivar matching_rules: List of rules to apply to match identifiers for new profile updates against existing profiles (if any). Rules are evaluated in the exact order specified in this array - the identity resolution algorithm will apply rules sequentially from first to last, and this order is preserved. 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 updated with the new data. If a rule matches to multiple existing profiles, those existing profiles will be merged into a single unique profile updated with the new data. All identifiers should match based on the matching condition (e.g. matchingAlgo) as per the identifierConfigs. + :ivar version: The current version number of the Identity Resolution Settings. Incremented on each successful update. + """ + + def __init__(self, version: Version, payload:Dict[str, Any], 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._solution = { + "store_id": store_id or self.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, prefer: 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 one provided, preventing accidental overwrites and responding with 412 Precondition Failed if they don't match. + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + + :returns: The updated IdentityResolutionSettingInstance + """ + return self._proxy.update(identity_resolution_settings_core=identity_resolution_settings_core, if_match=if_match, prefer=prefer, ) + + async def update_async(self, identity_resolution_settings_core: IdentityResolutionSettingsCore, if_match: Union[str, object]=values.unset, prefer: 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 one provided, preventing accidental overwrites and responding with 412 Precondition Failed if they don't match. + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + + :returns: The updated IdentityResolutionSettingInstance + """ + return await self._proxy.update_async(identity_resolution_settings_core=identity_resolution_settings_core, if_match=if_match, prefer=prefer, ) + + def update_with_http_info(self, identity_resolution_settings_core: IdentityResolutionSettingsCore, if_match: Union[str, object]=values.unset, prefer: 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 one provided, preventing accidental overwrites and responding with 412 Precondition Failed if they don't match. + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + + :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, prefer=prefer, ) + + async def update_with_http_info_async(self, identity_resolution_settings_core: IdentityResolutionSettingsCore, if_match: Union[str, object]=values.unset, prefer: 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 one provided, preventing accidental overwrites and responding with 412 Precondition Failed if they don't match. + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + + :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, prefer=prefer, ) + + def __repr__(self) -> str: + """ + 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): + + class IdentifierConfig(object): + """ + :ivar id_type: Name of the identifier to use for identity resolution. Usual values are email, phone, user_id etc. + :ivar matching_algo: The algorithm to use for matching the identifier's value. Possible value are exact or fuzzy Exact will match the identifier exactly, while fuzzy (low precision) will allow for some variations. + :ivar matching_threshold: The threshold as percentage to use for fuzzy matching. A value between 50 and 99. Required for fuzzy algo. + :ivar limit: Maximum number of value to retain for this identifier for a profile. + :ivar limit_policy: Policy to apply when the number of values for the identifier exceeds the limit. The extra values will be removed using either fifo or lifo policy to make them compliant. fifo/lifo will be applied based on the event timestamp of the request that added the identifier. + :ivar enforce_unique: True means only one profile will have the identifier, forcing profiles that share it to merge. False would allow multiple profiles to share the identifier and only merge if there is a matching MatchingRule. + :ivar normalization: Normalization to apply to the identifier value before storing and matching. + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.id_type: Optional[str] = payload.get("id_type") + self.matching_algo: Optional["IdentityResolutionSettingInstance.str"] = payload.get("matching_algo") + self.matching_threshold: Optional[int] = payload.get("matching_threshold") + self.limit: Optional[int] = payload.get("limit") + self.limit_policy: Optional["IdentityResolutionSettingInstance.str"] = payload.get("limit_policy") + self.enforce_unique: Optional[bool] = payload.get("enforce_unique") + self.normalization: Optional["IdentityResolutionSettingInstance.str"] = payload.get("normalization") + + def to_dict(self): + return { + + "id_type": self.id_type, + "matching_algo": self.matching_algo, + "matching_threshold": self.matching_threshold, + "limit": self.limit, + "limit_policy": self.limit_policy, + "enforce_unique": self.enforce_unique, + "normalization": self.normalization, + } + + class IdentityResolutionSettingsCore(object): + """ + :ivar identifier_configs: List of identifier, traits to use as identifiers for identity resolution. + :ivar matching_rules: List of rules to apply to match identifiers for new profile updates against existing profiles (if any). Rules are evaluated in the exact order specified in this array - the identity resolution algorithm will apply rules sequentially from first to last, and this order is preserved. 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 updated with the new data. If a rule matches to multiple existing profiles, those existing profiles will be merged into a single unique profile updated with the new data. All identifiers should match based on the matching condition (e.g. matchingAlgo) as per the identifierConfigs. + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.identifier_configs: Optional[List[IdentityResolutionSettingList.IdentifierConfig]] = payload.get("identifier_configs") + self.matching_rules: Optional[List[str]] = payload.get("matching_rules") + + def to_dict(self): + return { + + "identifier_configs": [identifier_configs.to_dict() for identifier_configs in self.identifier_configs] if self.identifier_configs is not None else None, + "matching_rules": self.matching_rules, + } + + + 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, prefer: 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 + + if not (prefer is values.unset or (isinstance(prefer, str) and not prefer)): + headers['Prefer'] = prefer + + 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, prefer: 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 one provided, preventing accidental overwrites and responding with 412 Precondition Failed if they don't match. + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + + :returns: The updated IdentityResolutionSettingInstance + """ + payload, _, _ = self._update(identity_resolution_settings_core=identity_resolution_settings_core, if_match=if_match, prefer=prefer) + 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, prefer: 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 one provided, preventing accidental overwrites and responding with 412 Precondition Failed if they don't match. + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + + :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, prefer=prefer) + 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, prefer: 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 + + + if not (prefer is values.unset or (isinstance(prefer, str) and not prefer)): + headers['Prefer'] = prefer + + + 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, prefer: 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 one provided, preventing accidental overwrites and responding with 412 Precondition Failed if they don't match. + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + + :returns: The updated IdentityResolutionSettingInstance + """ + payload, _, _ = await self._update_async(identity_resolution_settings_core=identity_resolution_settings_core, if_match=if_match, prefer=prefer) + 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, prefer: 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 one provided, preventing accidental overwrites and responding with 412 Precondition Failed if they don't match. + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + + :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, prefer=prefer) + 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 to use for identity resolution. Usual values are email, phone, user_id etc. + :ivar matching_algo: The algorithm to use for matching the identifier's value. Possible value are exact or fuzzy Exact will match the identifier exactly, while fuzzy (low precision) will allow for some variations. + :ivar matching_threshold: The threshold as percentage to use for fuzzy matching. A value between 50 and 99. Required for fuzzy algo. + :ivar limit: Maximum number of value to retain for this identifier for a profile. + :ivar limit_policy: Policy to apply when the number of values for the identifier exceeds the limit. The extra values will be removed using either fifo or lifo policy to make them compliant. fifo/lifo will be applied based on the event timestamp of the request that added the identifier. + :ivar enforce_unique: True means only one profile will have the identifier, forcing profiles that share it to merge. False would allow multiple profiles to share the identifier and only merge if there is a matching MatchingRule. + :ivar normalization: Normalization to apply to the identifier value before storing and matching. + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.id_type: Optional[str] = payload.get("id_type") + self.matching_algo: Optional["IdentityResolutionSettingInstance.str"] = payload.get("matching_algo") + self.matching_threshold: Optional[int] = payload.get("matching_threshold") + self.limit: Optional[int] = payload.get("limit") + self.limit_policy: Optional["IdentityResolutionSettingInstance.str"] = payload.get("limit_policy") + self.enforce_unique: Optional[bool] = payload.get("enforce_unique") + self.normalization: Optional["IdentityResolutionSettingInstance.str"] = payload.get("normalization") + + def to_dict(self): + return { + + "id_type": self.id_type, + "matching_algo": self.matching_algo, + "matching_threshold": self.matching_threshold, + "limit": self.limit, + "limit_policy": self.limit_policy, + "enforce_unique": self.enforce_unique, + "normalization": self.normalization, + } + + class IdentityResolutionSettingsCore(object): + """ + :ivar identifier_configs: List of identifier, traits to use as identifiers for identity resolution. + :ivar matching_rules: List of rules to apply to match identifiers for new profile updates against existing profiles (if any). Rules are evaluated in the exact order specified in this array - the identity resolution algorithm will apply rules sequentially from first to last, and this order is preserved. 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 updated with the new data. If a rule matches to multiple existing profiles, those existing profiles will be merged into a single unique profile updated with the new data. All identifiers should match based on the matching condition (e.g. matchingAlgo) as per the identifierConfigs. + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.identifier_configs: Optional[List[IdentityResolutionSettingList.IdentifierConfig]] = payload.get("identifier_configs") + self.matching_rules: Optional[List[str]] = payload.get("matching_rules") + + def to_dict(self): + return { + + "identifier_configs": [identifier_configs.to_dict() for identifier_configs in self.identifier_configs] if self.identifier_configs is not None else None, + "matching_rules": 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 000000000..166b2cfbd --- /dev/null +++ b/twilio/rest/memory/v1/import_.py @@ -0,0 +1,1058 @@ +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 datetime import date, datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator, Protocol +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 ResponseResource(Protocol): + pass + +''' +Nested response model for ColumnMappingItem +''' +class ColumnMappingItem: + def __init__(self,column_name: str, trait_group: str, trait_name: str): + self.column_name = column_name + self.trait_group = trait_group + self.trait_name = trait_name + + + +''' +Nested response model for CreateProfilesImportRequest +''' +class CreateProfilesImportRequest: + def __init__(self,filename: str, file_size: int, column_mappings: List[ImportList.ColumnMappingItem]): + self.filename = filename + self.file_size = file_size + self.column_mappings = column_mappings + + + +''' +Nested response model for FetchProfileImport200ResponseSummary +''' +class FetchProfileImport200ResponseSummary: + def __init__(self,errors: int, warnings: int): + self.errors = errors + self.warnings = warnings + + + + + +""" +Response model for ListProfileImports_200_response operations +""" +class ListProfileImports_200_responseResource: + def __init__(self,imports: List[str]): + """ + Initialize the ListProfileImports_200_responseResource + :param imports: + + """ + self.imports = imports + + +""" +Response model for FetchProfileImportV2_200_response operations +""" +class FetchProfileImportV2_200_responseResource: + def __init__(self,status: str, filename: str, created_at: datetime, updated_at: datetime, file_size: int, column_mappings: List[ColumnMappingItem], summary: FetchProfileImport200ResponseSummary): + """ + Initialize the FetchProfileImportV2_200_responseResource + :param status: Current processing status of the import task + :param filename: Original filename of the uploaded CSV + :param created_at: Timestamp when the import was created + :param updated_at: Timestamp when the import was last updated + :param file_size: Size of the uploaded file in bytes (1 byte to 100 MiB) + :param column_mappings: Mappings of CSV header columns to traits' fields + :param summary: + + """ + self.status = status + self.filename = filename + self.created_at = created_at + self.updated_at = updated_at + self.file_size = file_size + self.column_mappings = column_mappings + self.summary = summary + + +""" +Response model for CreateProfilesImport_201_response operations +""" +class CreateProfilesImport_201_responseResource: + def __init__(self,import_id: str, url: str): + """ + Initialize the CreateProfilesImport_201_responseResource + :param import_id: ID of the import task. + :param url: Pre-signed URL to upload the CSV via a single PUT request. + + """ + self.import_id = import_id + self.url = url + + +""" +Response model for FetchProfileImport_200_response operations +""" +class FetchProfileImport_200_responseResource: + def __init__(self,status: str, filename: str, created_at: datetime, updated_at: datetime, file_size: int, column_mappings: List[ColumnMappingItem], summary: FetchProfileImport200ResponseSummary): + """ + Initialize the FetchProfileImport_200_responseResource + :param status: Current processing status of the import task + :param filename: Original filename of the uploaded CSV + :param created_at: Timestamp when the import was created + :param updated_at: Timestamp when the import was last updated + :param file_size: Size of the uploaded file in bytes + :param column_mappings: Mappings of CSV header columns to traits' fields + :param summary: + + """ + self.status = status + self.filename = filename + self.created_at = created_at + self.updated_at = updated_at + self.file_size = file_size + self.column_mappings = column_mappings + self.summary = summary + + + + +class ImportInstance(InstanceResource): + + 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("column_name") + self.trait_group: Optional[str] = payload.get("trait_group") + self.trait_name: Optional[str] = payload.get("trait_name") + + def to_dict(self): + return { + + "column_name": self.column_name, + "trait_group": self.trait_group, + "trait_name": self.trait_name, + } + + class CreateProfilesImportRequest(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("file_size") + self.column_mappings: Optional[List[ImportList.ColumnMappingItem]] = payload.get("column_mappings") + + def to_dict(self): + return { + + "filename": self.filename, + "file_size": self.file_size, + "column_mappings": [column_mappings.to_dict() for column_mappings in self.column_mappings] if self.column_mappings is not None else None, + } + + class FetchProfileImport200ResponseSummary(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 { + + "": self.errors, + "": self.warnings, + } + + + + """ + :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: Optional[str] = None): + super().__init__(version) + + + self.import_id: Optional[str] = payload.get("importId") + self.url: Optional[str] = payload.get("url") + + + self._solution = { + "store_id": store_id or self.store_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'],) + return self._context + + + def create(self, create_profiles_import_request: CreateProfilesImportRequest) -> "ImportInstance": + """ + Create the ImportInstance + + :param create_profiles_import_request: + + :returns: The created ImportInstance + """ + return self._proxy.create(create_profiles_import_request, ) + async def create_async(self, create_profiles_import_request: CreateProfilesImportRequest) -> "ImportInstance": + """ + Asynchronous coroutine to create the ImportInstance + + :param create_profiles_import_request: + + :returns: The created ImportInstance + """ + return await self._proxy.create_async(create_profiles_import_request, ) + + def create_with_http_info(self, create_profiles_import_request: CreateProfilesImportRequest) -> ApiResponse: + """ + Create the ImportInstance with HTTP info + + :param create_profiles_import_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info(create_profiles_import_request, ) + + async def create_with_http_info_async(self, create_profiles_import_request: CreateProfilesImportRequest) -> ApiResponse: + """ + Asynchronous coroutine to create the ImportInstance with HTTP info + + :param create_profiles_import_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_async(create_profiles_import_request, ) + + + def create(self, create_profiles_import_request: CreateProfilesImportRequest) -> "ImportInstance": + """ + Create the ImportInstance + + :param create_profiles_import_request: + + :returns: The created ImportInstance + """ + return self._proxy.create(create_profiles_import_request, ) + async def create_async(self, create_profiles_import_request: CreateProfilesImportRequest) -> "ImportInstance": + """ + Asynchronous coroutine to create the ImportInstance + + :param create_profiles_import_request: + + :returns: The created ImportInstance + """ + return await self._proxy.create_async(create_profiles_import_request, ) + + def create_with_http_info(self, create_profiles_import_request: CreateProfilesImportRequest) -> ApiResponse: + """ + Create the ImportInstance with HTTP info + + :param create_profiles_import_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info(create_profiles_import_request, ) + + async def create_with_http_info_async(self, create_profiles_import_request: CreateProfilesImportRequest) -> ApiResponse: + """ + Asynchronous coroutine to create the ImportInstance with HTTP info + + :param create_profiles_import_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_async(create_profiles_import_request, ) + + + 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 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): + + 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("column_name") + self.trait_group: Optional[str] = payload.get("trait_group") + self.trait_name: Optional[str] = payload.get("trait_name") + + def to_dict(self): + return { + + "column_name": self.column_name, + "trait_group": self.trait_group, + "trait_name": self.trait_name, + } + + class CreateProfilesImportRequest(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("file_size") + self.column_mappings: Optional[List[ImportList.ColumnMappingItem]] = payload.get("column_mappings") + + def to_dict(self): + return { + + "filename": self.filename, + "file_size": self.file_size, + "column_mappings": [column_mappings.to_dict() for column_mappings in self.column_mappings] if self.column_mappings is not None else None, + } + + class FetchProfileImport200ResponseSummary(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 { + + "": self.errors, + "": self.warnings, + } + + + def __init__(self, version: Version, store_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 + """ + 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_request: CreateProfilesImportRequest) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_profiles_import_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_profiles_import_request: CreateProfilesImportRequest) -> ImportInstance: + """ + Create the ImportInstance + + :param create_profiles_import_request: + + :returns: The created ImportInstance + """ + payload, _, _ = self._create(create_profiles_import_request=create_profiles_import_request) + return ImportInstance( + self._version, + payload, + store_id=self._solution['store_id'] + ) + + def create_with_http_info(self, create_profiles_import_request: CreateProfilesImportRequest) -> ApiResponse: + """ + Create the ImportInstance and return response metadata + + :param create_profiles_import_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(create_profiles_import_request=create_profiles_import_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_request: CreateProfilesImportRequest) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_profiles_import_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_profiles_import_request: CreateProfilesImportRequest) -> ImportInstance: + """ + Asynchronous coroutine to create the ImportInstance + + :param create_profiles_import_request: + + :returns: The created ImportInstance + """ + payload, _, _ = await self._create_async(create_profiles_import_request=create_profiles_import_request) + return ImportInstance( + self._version, + payload, + store_id=self._solution['store_id'] + ) + + async def create_with_http_info_async(self, create_profiles_import_request: CreateProfilesImportRequest) -> ApiResponse: + """ + Asynchronous coroutine to create the ImportInstance and return response metadata + + :param create_profiles_import_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(create_profiles_import_request=create_profiles_import_request) + instance = ImportInstance( + self._version, + payload, + store_id=self._solution['store_id'] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + + def _create(self, create_profiles_import_request: CreateProfilesImportRequest) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_profiles_import_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_profiles_import_request: CreateProfilesImportRequest) -> ImportInstance: + """ + Create the ImportInstance + + :param create_profiles_import_request: + + :returns: The created ImportInstance + """ + payload, _, _ = self._create(create_profiles_import_request=create_profiles_import_request) + return ImportInstance( + self._version, + payload, + store_id=self._solution['store_id'] + ) + + def create_with_http_info(self, create_profiles_import_request: CreateProfilesImportRequest) -> ApiResponse: + """ + Create the ImportInstance and return response metadata + + :param create_profiles_import_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(create_profiles_import_request=create_profiles_import_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_request: CreateProfilesImportRequest) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_profiles_import_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_profiles_import_request: CreateProfilesImportRequest) -> ImportInstance: + """ + Asynchronous coroutine to create the ImportInstance + + :param create_profiles_import_request: + + :returns: The created ImportInstance + """ + payload, _, _ = await self._create_async(create_profiles_import_request=create_profiles_import_request) + return ImportInstance( + self._version, + payload, + store_id=self._solution['store_id'] + ) + + async def create_with_http_info_async(self, create_profiles_import_request: CreateProfilesImportRequest) -> ApiResponse: + """ + Asynchronous coroutine to create the ImportInstance and return response metadata + + :param create_profiles_import_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(create_profiles_import_request=create_profiles_import_request) + instance = ImportInstance( + self._version, + payload, + store_id=self._solution['store_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) -> ImportInstance: + """ + Fetch the ImportInstance + + + :returns: The fetched ImportInstance + """ + payload, _, _ = self._fetch() + return ImportInstance( + self._version, + payload, + store_id=self._solution['store_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'], + + ) + 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'], + + ) + + 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'], + + ) + 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) -> ImportInstance: + """ + Fetch the ImportInstance + + + :returns: The fetched ImportInstance + """ + payload, _, _ = self._fetch() + return ImportInstance( + self._version, + payload, + store_id=self._solution['store_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'], + + ) + 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'], + + ) + + 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'], + + ) + 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: Dict[str, Any]) -> ImportInstance: + """ + Build an instance of ImportInstance + + :param payload: Payload response from the API + """ + return ImportInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + + + +class ImportPage(TokenPagination): + + def get_instance(self, payload: Dict[str, Any]) -> ImportInstance: + """ + Build an instance of ImportInstance + + :param payload: Payload response from the API + """ + return ImportInstance(self._version, payload) + + 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("column_name") + self.trait_group: Optional[str] = payload.get("trait_group") + self.trait_name: Optional[str] = payload.get("trait_name") + + def to_dict(self): + return { + + "column_name": self.column_name, + "trait_group": self.trait_group, + "trait_name": self.trait_name, + } + + class CreateProfilesImportRequest(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("file_size") + self.column_mappings: Optional[List[ImportList.ColumnMappingItem]] = payload.get("column_mappings") + + def to_dict(self): + return { + + "filename": self.filename, + "file_size": self.file_size, + "column_mappings": [column_mappings.to_dict() for column_mappings in self.column_mappings] if self.column_mappings is not None else None, + } + + class FetchProfileImport200ResponseSummary(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 { + + "": self.errors, + "": self.warnings, + } + + + def __init__(self, version: Version): + """ + Initialize the ImportList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + + + + + + def get(self, store_id: str) -> ImportContext: + """ + Constructs a ImportContext + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + """ + return ImportContext(self._version, store_id=store_id) + + def __call__(self, store_id: str) -> ImportContext: + """ + Constructs a ImportContext + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + """ + return ImportContext(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/lookup.py b/twilio/rest/memory/v1/lookup.py new file mode 100644 index 000000000..5f2e41299 --- /dev/null +++ b/twilio/rest/memory/v1/lookup.py @@ -0,0 +1,343 @@ +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 datetime import date, datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator, Protocol +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 LookupInstance(InstanceResource): + + class Identifier(object): + """ + :ivar id_type: Identifier type as configured in the service's Identity Resolution Settings. Must match an `idType` defined in the corresponding identifier settings and must satisfy the same length constraints. + :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("id_type") + self.value: Optional[str] = payload.get("value") + + def to_dict(self): + return { + + "id_type": self.id_type, + "value": self.value, + } + + + + """ + :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: Optional[str] = None): + super().__init__(version) + + + self.normalized_value: Optional[str] = payload.get("normalizedValue") + self.profiles: Optional[List[str]] = payload.get("profiles") + + + self._solution = { + "store_id": store_id or self.store_id, + } + self._context: Optional[LookupContext] = None + + @property + def _proxy(self) -> "LookupContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: LookupContext for this LookupInstance + """ + if self._context is None: + self._context = LookupContext(self._version, store_id=self._solution['store_id'],) + return self._context + + + def create(self, identifier: Identifier) -> "LookupInstance": + """ + Create the LookupInstance + + :param identifier: + + :returns: The created LookupInstance + """ + return self._proxy.create(identifier, ) + async def create_async(self, identifier: Identifier) -> "LookupInstance": + """ + Asynchronous coroutine to create the LookupInstance + + :param identifier: + + :returns: The created LookupInstance + """ + return await self._proxy.create_async(identifier, ) + + def create_with_http_info(self, identifier: Identifier) -> ApiResponse: + """ + Create the LookupInstance with HTTP info + + :param identifier: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info(identifier, ) + + async def create_with_http_info_async(self, identifier: Identifier) -> ApiResponse: + """ + Asynchronous coroutine to create the LookupInstance with HTTP info + + :param identifier: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_async(identifier, ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) + return ''.format(context) + +class LookupContext(InstanceContext): + + class Identifier(object): + """ + :ivar id_type: Identifier type as configured in the service's Identity Resolution Settings. Must match an `idType` defined in the corresponding identifier settings and must satisfy the same length constraints. + :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("id_type") + self.value: Optional[str] = payload.get("value") + + def to_dict(self): + return { + + "id_type": self.id_type, + "value": self.value, + } + + + def __init__(self, version: Version, store_id: str): + """ + Initialize the LookupContext + + :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({}) + + + 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({}) + + + 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: + """ + Asynchronous coroutine to 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: + """ + Asynchronous coroutine to 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 + """ + 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. Must match an `idType` defined in the corresponding identifier settings and must satisfy the same length constraints. + :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("id_type") + self.value: Optional[str] = payload.get("value") + + def to_dict(self): + return { + + "id_type": self.id_type, + "value": self.value, + } + + + def __init__(self, version: Version): + """ + Initialize the LookupList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + + + + + + def get(self, store_id: str) -> LookupContext: + """ + Constructs a LookupContext + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + """ + return LookupContext(self._version, store_id=store_id) + + def __call__(self, store_id: str) -> LookupContext: + """ + Constructs a LookupContext + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + """ + return LookupContext(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/observation.py b/twilio/rest/memory/v1/observation.py new file mode 100644 index 000000000..cb12ccf8d --- /dev/null +++ b/twilio/rest/memory/v1/observation.py @@ -0,0 +1,1077 @@ +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 datetime import date, datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator, Protocol +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 ResponseResource(Protocol): + pass + +''' +Nested response model for CreateObservationsRequest +''' +class CreateObservationsRequest: + def __init__(self,observations: List[ObservationList.ObservationCore]): + self.observations = observations + + + +''' +Nested response model for ObservationCore +''' +class ObservationCore: + def __init__(self,content: str, occurred_at: datetime, source: str, conversation_ids: List[str]): + self.content = content + self.occurred_at = occurred_at + self.source = source + self.conversation_ids = conversation_ids + + + +''' +Nested response model for ObservationsMeta +''' +class ObservationsMeta: + def __init__(self,key: str, page_size: int, next_token: str, previous_token: str): + self.key = key + self.page_size = page_size + self.next_token = next_token + self.previous_token = previous_token + + + + + +""" +Response model for ObservationCreatedResponse operations +""" +class ObservationCreatedResponseResource: + def __init__(self,message: str): + """ + Initialize the ObservationCreatedResponseResource + :param message: Confirmation message for the operation. + + """ + self.message = message + + +""" +Response model for TwilioError operations +""" +class TwilioErrorResource: + def __init__(self,code: int, message: str, more_info: str, status: int): + """ + Initialize the TwilioErrorResource + :param code: The Twilio error code. + :param message: A human readable message describing the error. + :param more_info: A URL to a [Twilio error directory](https://www.twilio.com/docs/api/errors) page with more information about the error code. + :param status: The HTTP status code for the error. + + """ + self.code = code + self.message = message + self.more_info = more_info + self.status = status + + +""" +Response model for DeleteProfileObservation_202_response operations +""" +class DeleteProfileObservation_202_responseResource: + def __init__(self,message: str): + """ + Initialize the DeleteProfileObservation_202_responseResource + :param message: + + """ + self.message = message + + +""" +Response model for ListProfileObservations_200_response operations +""" +class ListProfileObservations_200_responseResource: + def __init__(self,observations: List[Dict[str, object]], meta: ObservationsMeta): + """ + Initialize the ListProfileObservations_200_responseResource + :param observations: + :param meta: + + """ + self.observations = observations + self.meta = meta + + +""" +Response model for UpdateProfileObservation_202_response operations +""" +class UpdateProfileObservation_202_responseResource: + def __init__(self,message: str): + """ + Initialize the UpdateProfileObservation_202_responseResource + :param message: + + """ + self.message = message + + + + +class ObservationInstance(InstanceResource): + + 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("occurred_at") + self.source: Optional[str] = payload.get("source") + self.conversation_ids: Optional[List[str]] = payload.get("conversation_ids") + + def to_dict(self): + return { + + "content": self.content, + "occurred_at": self.occurred_at, + "source": self.source, + "conversation_ids": self.conversation_ids, + } + + class ObservationsMeta(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("page_size") + self.next_token: Optional[str] = payload.get("next_token") + self.previous_token: Optional[str] = payload.get("previous_token") + + def to_dict(self): + return { + + "": self.key, + "": self.page_size, + "": self.next_token, + "": self.previous_token, + } + + + + """ + :ivar message: Confirmation message for the operation. + """ + + def __init__(self, version: Version, payload:ResponseResource, store_id: Optional[str] = None, profile_id: Optional[str] = None, observation_id: Optional[str] = None): + super().__init__(version) + + + self.message: Optional[str] = payload.get("message") + + + self._solution = { + "store_id": store_id or self.store_id, + "profile_id": profile_id or self.profile_id, + "observation_id": observation_id or self.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 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 + """ + return self._proxy.create(create_observations_request, accept_encoding=accept_encoding, content_encoding=content_encoding, ) + async def create_async(self, create_observations_request: CreateObservationsRequest, accept_encoding: Union[str, object]=values.unset, content_encoding: Union[str, object]=values.unset) -> "ObservationInstance": + """ + Asynchronous coroutine to 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 + """ + return await self._proxy.create_async(create_observations_request, accept_encoding=accept_encoding, content_encoding=content_encoding, ) + + 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 with HTTP info + + :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 + """ + return self._proxy.create_with_http_info(create_observations_request, accept_encoding=accept_encoding, content_encoding=content_encoding, ) + + 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: + """ + Asynchronous coroutine to create the ObservationInstance with HTTP info + + :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 + """ + return await self._proxy.create_with_http_info_async(create_observations_request, accept_encoding=accept_encoding, content_encoding=content_encoding, ) + + + 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 update(self, observation_core: ObservationCore) -> "ObservationInstance": + """ + Update the ObservationInstance + + :param observation_core: + + :returns: The updated ObservationInstance + """ + return self._proxy.update(observation_core=observation_core, ) + + async def update_async(self, observation_core: ObservationCore) -> "ObservationInstance": + """ + Asynchronous coroutine to update the ObservationInstance + + :param observation_core: + + :returns: The updated ObservationInstance + """ + return await self._proxy.update_async(observation_core=observation_core, ) + + def update_with_http_info(self, observation_core: ObservationCore) -> ApiResponse: + """ + Update the ObservationInstance with HTTP info + + :param observation_core: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info(observation_core=observation_core, ) + + async def update_with_http_info_async(self, observation_core: ObservationCore) -> ApiResponse: + """ + Asynchronous coroutine to update the ObservationInstance with HTTP info + + :param observation_core: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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): + + 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("occurred_at") + self.source: Optional[str] = payload.get("source") + self.conversation_ids: Optional[List[str]] = payload.get("conversation_ids") + + def to_dict(self): + return { + + "content": self.content, + "occurred_at": self.occurred_at, + "source": self.source, + "conversation_ids": self.conversation_ids, + } + + class ObservationsMeta(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("page_size") + self.next_token: Optional[str] = payload.get("next_token") + self.previous_token: Optional[str] = payload.get("previous_token") + + def to_dict(self): + return { + + "": self.key, + "": self.page_size, + "": self.next_token, + "": self.previous_token, + } + + + 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 _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({}) + + + if not (accept_encoding is values.unset or (isinstance(accept_encoding, str) and not accept_encoding)): + headers['Accept-Encoding'] = accept_encoding + + if not (content_encoding is values.unset or (isinstance(content_encoding, str) and not content_encoding)): + headers['Content-Encoding'] = content_encoding + + 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'], + observation_id=self._solution['observation_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'], + observation_id=self._solution['observation_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({}) + + + if not (accept_encoding is values.unset or (isinstance(accept_encoding, str) and not accept_encoding)): + headers['Accept-Encoding'] = accept_encoding + + if not (content_encoding is values.unset or (isinstance(content_encoding, str) and not content_encoding)): + headers['Content-Encoding'] = content_encoding + + 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: + """ + Asynchronous coroutine to 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'], + observation_id=self._solution['observation_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: + """ + Asynchronous coroutine to 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'], + observation_id=self._solution['observation_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({}) + + + + 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 _update(self, observation_core: ObservationCore) -> tuple: + """ + Internal helper for update 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.update_with_response_info(method='PATCH', uri=self._uri, data=data, headers=headers) + + def update(self, observation_core: ObservationCore) -> ObservationInstance: + """ + Update the ObservationInstance + + :param observation_core: + + :returns: The updated ObservationInstance + """ + payload, _, _ = self._update(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 update_with_http_info(self, observation_core: ObservationCore) -> ApiResponse: + """ + Update the ObservationInstance and return response metadata + + :param observation_core: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(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 _update_async(self, observation_core: ObservationCore) -> tuple: + """ + Internal async helper for update 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.update_with_response_info_async(method='PATCH', uri=self._uri, data=data, headers=headers) + + async def update_async(self, observation_core: ObservationCore) -> ObservationInstance: + """ + Asynchronous coroutine to update the ObservationInstance + + :param observation_core: + + :returns: The updated ObservationInstance + """ + payload, _, _ = await self._update_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 update_with_http_info_async(self, observation_core: ObservationCore) -> ApiResponse: + """ + Asynchronous coroutine to update the ObservationInstance and return response metadata + + :param observation_core: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_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) + + 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("occurred_at") + self.source: Optional[str] = payload.get("source") + self.conversation_ids: Optional[List[str]] = payload.get("conversation_ids") + + def to_dict(self): + return { + + "content": self.content, + "occurred_at": self.occurred_at, + "source": self.source, + "conversation_ids": self.conversation_ids, + } + + class ObservationsMeta(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("page_size") + self.next_token: Optional[str] = payload.get("next_token") + self.previous_token: Optional[str] = payload.get("previous_token") + + def to_dict(self): + return { + + "": self.key, + "": self.page_size, + "": self.next_token, + "": self.previous_token, + } + + + def __init__(self, version: Version): + """ + Initialize the ObservationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + + + + + + def get(self, store_id: str, profile_id: str, observation_id: str) -> ObservationContext: + """ + Constructs a ObservationContext + + :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. + """ + return ObservationContext(self._version, store_id=store_id, profile_id=profile_id, observation_id=observation_id) + + def __call__(self, store_id: str, profile_id: str, observation_id: str) -> ObservationContext: + """ + Constructs a ObservationContext + + :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. + """ + return ObservationContext(self._version, store_id=store_id, profile_id=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/profile.py b/twilio/rest/memory/v1/profile.py new file mode 100644 index 000000000..25fdcc72c --- /dev/null +++ b/twilio/rest/memory/v1/profile.py @@ -0,0 +1,1022 @@ +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 datetime import date, datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator, Protocol +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 ResponseResource(Protocol): + pass + +''' +Nested response model for ProfileData +''' +class ProfileData: + def __init__(self,traits: Dict[str, Dict[str, object]]): + self.traits = traits + + + +''' +Nested response model for ProfilePatch +''' +class ProfilePatch: + def __init__(self,traits: Dict[str, Dict[str, object]]): + self.traits = traits + + + +''' +Nested response model for ProfilesMeta +''' +class ProfilesMeta: + def __init__(self,key: str, page_size: int, next_token: str, previous_token: str): + self.key = key + self.page_size = page_size + self.next_token = next_token + self.previous_token = previous_token + + + + + +""" +Response model for ListProfiles_200_response operations +""" +class ListProfiles_200_responseResource: + def __init__(self,profiles: List[str], meta: ProfilesMeta): + """ + Initialize the ListProfiles_200_responseResource + :param profiles: + :param meta: + + """ + self.profiles = profiles + self.meta = meta + + +""" +Response model for UpdateProfileTraits_202_response operations +""" +class UpdateProfileTraits_202_responseResource: + def __init__(self,message: str): + """ + Initialize the UpdateProfileTraits_202_responseResource + :param message: + + """ + self.message = message + + +""" +Response model for DeleteProfile_202_response operations +""" +class DeleteProfile_202_responseResource: + def __init__(self,message: str): + """ + Initialize the DeleteProfile_202_responseResource + :param message: + + """ + self.message = message + + +""" +Response model for CreateProfile_202_response operations +""" +class CreateProfile_202_responseResource: + def __init__(self,id: str, message: str): + """ + Initialize the CreateProfile_202_responseResource + :param id: The canonical profile ID. + :param message: + + """ + self.id = id + self.message = message + + +""" +Response model for Profile operations +""" +class ProfileResource: + def __init__(self,id: str, created_at: datetime, traits: Dict[str, Dict[str, object]]): + """ + Initialize the ProfileResource + :param id: The canonical profile ID. + :param created_at: The time the profile was created. + :param traits: Multiple trait groups. + + """ + self.id = id + self.created_at = created_at + self.traits = traits + + + + +class ProfileInstance(InstanceResource): + + 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("page_size") + self.next_token: Optional[str] = payload.get("next_token") + self.previous_token: Optional[str] = payload.get("previous_token") + + def to_dict(self): + return { + + "": self.key, + "": self.page_size, + "": self.next_token, + "": self.previous_token, + } + + + + """ + :ivar id: The canonical profile ID. + :ivar message: + """ + + def __init__(self, version: Version, payload:ResponseResource, store_id: Optional[str] = None, profile_id: Optional[str] = None): + super().__init__(version) + + + self.id: Optional[str] = payload.get("id") + self.message: Optional[str] = payload.get("message") + + + self._solution = { + "store_id": store_id or self.store_id, + "profile_id": profile_id or self.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 create(self, profile_data: ProfileData) -> "ProfileInstance": + """ + Create the ProfileInstance + + :param profile_data: + + :returns: The created ProfileInstance + """ + return self._proxy.create(profile_data, ) + async def create_async(self, profile_data: ProfileData) -> "ProfileInstance": + """ + Asynchronous coroutine to create the ProfileInstance + + :param profile_data: + + :returns: The created ProfileInstance + """ + return await self._proxy.create_async(profile_data, ) + + def create_with_http_info(self, profile_data: ProfileData) -> ApiResponse: + """ + Create the ProfileInstance with HTTP info + + :param profile_data: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info(profile_data, ) + + async def create_with_http_info_async(self, profile_data: ProfileData) -> ApiResponse: + """ + Asynchronous coroutine to create the ProfileInstance with HTTP info + + :param profile_data: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_async(profile_data, ) + + + 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 update(self, profile_patch: ProfilePatch) -> "ProfileInstance": + """ + Update the ProfileInstance + + :param profile_patch: + + :returns: The updated ProfileInstance + """ + return self._proxy.update(profile_patch=profile_patch, ) + + async def update_async(self, profile_patch: ProfilePatch) -> "ProfileInstance": + """ + Asynchronous coroutine to update the ProfileInstance + + :param profile_patch: + + :returns: The updated ProfileInstance + """ + return await self._proxy.update_async(profile_patch=profile_patch, ) + + def update_with_http_info(self, profile_patch: ProfilePatch) -> ApiResponse: + """ + Update the ProfileInstance with HTTP info + + :param profile_patch: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info(profile_patch=profile_patch, ) + + async def update_with_http_info_async(self, profile_patch: ProfilePatch) -> ApiResponse: + """ + Asynchronous coroutine to update the ProfileInstance with HTTP info + + :param profile_patch: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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): + + 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("page_size") + self.next_token: Optional[str] = payload.get("next_token") + self.previous_token: Optional[str] = payload.get("previous_token") + + def to_dict(self): + return { + + "": self.key, + "": self.page_size, + "": self.next_token, + "": self.previous_token, + } + + + 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 _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({}) + + + 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'], + profile_id=self._solution['profile_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'], + profile_id=self._solution['profile_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({}) + + + 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: + """ + Asynchronous coroutine to 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'], + profile_id=self._solution['profile_id'] + ) + + async def create_with_http_info_async(self, profile_data: ProfileData) -> ApiResponse: + """ + Asynchronous coroutine to 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'], + profile_id=self._solution['profile_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({}) + + + + 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 _update(self, profile_patch: ProfilePatch) -> tuple: + """ + Internal helper for update 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.update_with_response_info(method='PATCH', uri=self._uri, data=data, headers=headers) + + def update(self, profile_patch: ProfilePatch) -> ProfileInstance: + """ + Update the ProfileInstance + + :param profile_patch: + + :returns: The updated ProfileInstance + """ + payload, _, _ = self._update(profile_patch=profile_patch) + return ProfileInstance( + self._version, + payload, + store_id=self._solution['store_id'], + profile_id=self._solution['profile_id'] + ) + + def update_with_http_info(self, profile_patch: ProfilePatch) -> ApiResponse: + """ + Update the ProfileInstance and return response metadata + + :param profile_patch: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(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 _update_async(self, profile_patch: ProfilePatch) -> tuple: + """ + Internal async helper for update 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.update_with_response_info_async(method='PATCH', uri=self._uri, data=data, headers=headers) + + async def update_async(self, profile_patch: ProfilePatch) -> ProfileInstance: + """ + Asynchronous coroutine to update the ProfileInstance + + :param profile_patch: + + :returns: The updated ProfileInstance + """ + payload, _, _ = await self._update_async(profile_patch=profile_patch) + return ProfileInstance( + self._version, + payload, + store_id=self._solution['store_id'], + profile_id=self._solution['profile_id'] + ) + + async def update_with_http_info_async(self, profile_patch: ProfilePatch) -> ApiResponse: + """ + Asynchronous coroutine to update the ProfileInstance and return response metadata + + :param profile_patch: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_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: Dict[str, Any]) -> ProfileInstance: + """ + Build an instance of ProfileInstance + + :param payload: Payload response from the API + """ + return ProfileInstance(self._version, payload) + + 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("page_size") + self.next_token: Optional[str] = payload.get("next_token") + self.previous_token: Optional[str] = payload.get("previous_token") + + def to_dict(self): + return { + + "": self.key, + "": self.page_size, + "": self.next_token, + "": self.previous_token, + } + + + def __init__(self, version: Version): + """ + Initialize the ProfileList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + + + + + + def get(self, store_id: str, profile_id: str) -> ProfileContext: + """ + Constructs a ProfileContext + + :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. + """ + return ProfileContext(self._version, store_id=store_id, profile_id=profile_id) + + def __call__(self, store_id: str, profile_id: str) -> ProfileContext: + """ + Constructs a ProfileContext + + :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. + """ + return ProfileContext(self._version, store_id=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 000000000..62319ec23 --- /dev/null +++ b/twilio/rest/memory/v1/recall.py @@ -0,0 +1,591 @@ +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 datetime import date, datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator, Protocol +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 RecallInstance(InstanceResource): + + 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 { + + "": self.text, + } + + 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. + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.conversation_id: Optional[str] = payload.get("conversation_id") + self.query: Optional[str] = payload.get("query") + self.begin_date: Optional[datetime] = payload.get("begin_date") + self.end_date: Optional[datetime] = payload.get("end_date") + self.communications_limit: Optional[int] = payload.get("communications_limit") + self.observations_limit: Optional[int] = payload.get("observations_limit") + self.summaries_limit: Optional[int] = payload.get("summaries_limit") + self.relevance_threshold: Optional[float] = payload.get("relevance_threshold") + + def to_dict(self): + return { + + "conversation_id": self.conversation_id, + "query": self.query, + "begin_date": self.begin_date, + "end_date": self.end_date, + "communications_limit": self.communications_limit, + "observations_limit": self.observations_limit, + "summaries_limit": self.summaries_limit, + "relevance_threshold": 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("profile_id") + self.address: Optional[str] = payload.get("address") + self.channel: Optional[str] = payload.get("channel") + + def to_dict(self): + return { + + "": self.id, + "": self.name, + "": self.type.to_dict() if self.type is not None else None , + "": self.profile_id, + "": self.address, + "": self.channel, + } + + + + class ParticipantType(object): + HUMAN_AGENT = "HUMAN_AGENT" + CUSTOMER = "CUSTOMER" + AI_AGENT = "AI_AGENT" + + """ + :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: Optional[str] = None, profile_id: Optional[str] = None): + super().__init__(version) + + + self.observations: Optional[List[Dict[str, object]]] = payload.get("observations") + self.summaries: Optional[List[Dict[str, object]]] = payload.get("summaries") + self.communications: Optional[List[str]] = payload.get("communications") + self.meta: Optional[str] = payload.get("meta") + + + self._solution = { + "store_id": store_id or self.store_id, + "profile_id": profile_id or self.profile_id, + } + self._context: Optional[RecallContext] = None + + @property + def _proxy(self) -> "RecallContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RecallContext for this RecallInstance + """ + if self._context is None: + self._context = RecallContext(self._version, store_id=self._solution['store_id'], profile_id=self._solution['profile_id'],) + return self._context + + + def fetch(self, memory_retrieval_request: MemoryRetrievalRequest, accept_encoding: Union[str, object]=values.unset, content_encoding: Union[str, object]=values.unset) -> "RecallInstance": + """ + Fetch 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 fetched RecallInstance + """ + return self._proxy.fetch(memory_retrieval_request=memory_retrieval_request, accept_encoding=accept_encoding, content_encoding=content_encoding, ) + + async def fetch_async(self, memory_retrieval_request: MemoryRetrievalRequest, accept_encoding: Union[str, object]=values.unset, content_encoding: Union[str, object]=values.unset) -> "RecallInstance": + """ + Asynchronous coroutine to fetch 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 fetched RecallInstance + """ + return await self._proxy.fetch_async(memory_retrieval_request=memory_retrieval_request, accept_encoding=accept_encoding, content_encoding=content_encoding, ) + + def fetch_with_http_info(self, memory_retrieval_request: MemoryRetrievalRequest, accept_encoding: Union[str, object]=values.unset, content_encoding: Union[str, object]=values.unset) -> ApiResponse: + """ + Fetch the RecallInstance with HTTP info + + :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 + """ + return self._proxy.fetch_with_http_info(memory_retrieval_request=memory_retrieval_request, accept_encoding=accept_encoding, content_encoding=content_encoding, ) + + async def fetch_with_http_info_async(self, memory_retrieval_request: MemoryRetrievalRequest, accept_encoding: Union[str, object]=values.unset, content_encoding: Union[str, object]=values.unset) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RecallInstance with HTTP info + + :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 + """ + return await self._proxy.fetch_with_http_info_async(memory_retrieval_request=memory_retrieval_request, accept_encoding=accept_encoding, content_encoding=content_encoding, ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) + return ''.format(context) + +class RecallContext(InstanceContext): + + 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 { + + "": self.text, + } + + 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. + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.conversation_id: Optional[str] = payload.get("conversation_id") + self.query: Optional[str] = payload.get("query") + self.begin_date: Optional[datetime] = payload.get("begin_date") + self.end_date: Optional[datetime] = payload.get("end_date") + self.communications_limit: Optional[int] = payload.get("communications_limit") + self.observations_limit: Optional[int] = payload.get("observations_limit") + self.summaries_limit: Optional[int] = payload.get("summaries_limit") + self.relevance_threshold: Optional[float] = payload.get("relevance_threshold") + + def to_dict(self): + return { + + "conversation_id": self.conversation_id, + "query": self.query, + "begin_date": self.begin_date, + "end_date": self.end_date, + "communications_limit": self.communications_limit, + "observations_limit": self.observations_limit, + "summaries_limit": self.summaries_limit, + "relevance_threshold": 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("profile_id") + self.address: Optional[str] = payload.get("address") + self.channel: Optional[str] = payload.get("channel") + + def to_dict(self): + return { + + "": self.id, + "": self.name, + "": self.type.to_dict() if self.type is not None else None , + "": self.profile_id, + "": self.address, + "": self.channel, + } + + + def __init__(self, version: Version, store_id: str, profile_id: str): + """ + Initialize the RecallContext + + :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 _fetch(self, memory_retrieval_request: MemoryRetrievalRequest, accept_encoding: Union[str, object]=values.unset, content_encoding: Union[str, object]=values.unset) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + + headers = values.of({}) + + + if not (accept_encoding is values.unset or (isinstance(accept_encoding, str) and not accept_encoding)): + headers['Accept-Encoding'] = accept_encoding + + + if not (content_encoding is values.unset or (isinstance(content_encoding, str) and not content_encoding)): + headers['Content-Encoding'] = content_encoding + + + headers["Content-Type"] = "application/json" + + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info(method='POST', uri=self._uri, headers=headers) + + def fetch(self, memory_retrieval_request: MemoryRetrievalRequest, accept_encoding: Union[str, object]=values.unset, content_encoding: Union[str, object]=values.unset) -> RecallInstance: + """ + Fetch 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 fetched RecallInstance + """ + payload, _, _ = self._fetch(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 fetch_with_http_info(self, memory_retrieval_request: MemoryRetrievalRequest, accept_encoding: Union[str, object]=values.unset, content_encoding: Union[str, object]=values.unset) -> ApiResponse: + """ + Fetch 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._fetch(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 _fetch_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 fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + + headers = values.of({}) + + + if not (accept_encoding is values.unset or (isinstance(accept_encoding, str) and not accept_encoding)): + headers['Accept-Encoding'] = accept_encoding + + + if not (content_encoding is values.unset or (isinstance(content_encoding, str) and not content_encoding)): + headers['Content-Encoding'] = content_encoding + + + headers["Content-Type"] = "application/json" + + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async(method='POST', uri=self._uri, headers=headers) + + async def fetch_async(self, memory_retrieval_request: MemoryRetrievalRequest, accept_encoding: Union[str, object]=values.unset, content_encoding: Union[str, object]=values.unset) -> RecallInstance: + """ + Asynchronous coroutine to fetch 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 fetched RecallInstance + """ + payload, _, _ = await self._fetch_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 fetch_with_http_info_async(self, memory_retrieval_request: MemoryRetrievalRequest, accept_encoding: Union[str, object]=values.unset, content_encoding: Union[str, object]=values.unset) -> ApiResponse: + """ + Asynchronous coroutine to fetch 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._fetch_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 + """ + 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 { + + "": self.text, + } + + 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. + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.conversation_id: Optional[str] = payload.get("conversation_id") + self.query: Optional[str] = payload.get("query") + self.begin_date: Optional[datetime] = payload.get("begin_date") + self.end_date: Optional[datetime] = payload.get("end_date") + self.communications_limit: Optional[int] = payload.get("communications_limit") + self.observations_limit: Optional[int] = payload.get("observations_limit") + self.summaries_limit: Optional[int] = payload.get("summaries_limit") + self.relevance_threshold: Optional[float] = payload.get("relevance_threshold") + + def to_dict(self): + return { + + "conversation_id": self.conversation_id, + "query": self.query, + "begin_date": self.begin_date, + "end_date": self.end_date, + "communications_limit": self.communications_limit, + "observations_limit": self.observations_limit, + "summaries_limit": self.summaries_limit, + "relevance_threshold": 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("profile_id") + self.address: Optional[str] = payload.get("address") + self.channel: Optional[str] = payload.get("channel") + + def to_dict(self): + return { + + "": self.id, + "": self.name, + "": self.type.to_dict() if self.type is not None else None , + "": self.profile_id, + "": self.address, + "": self.channel, + } + + + def __init__(self, version: Version): + """ + Initialize the RecallList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + + + + + + def get(self, store_id: str, profile_id: str) -> RecallContext: + """ + Constructs a RecallContext + + :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. + """ + return RecallContext(self._version, store_id=store_id, profile_id=profile_id) + + def __call__(self, store_id: str, profile_id: str) -> RecallContext: + """ + Constructs a RecallContext + + :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. + """ + return RecallContext(self._version, store_id=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/revision.py b/twilio/rest/memory/v1/revision.py new file mode 100644 index 000000000..36531018b --- /dev/null +++ b/twilio/rest/memory/v1/revision.py @@ -0,0 +1,174 @@ +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 datetime import date, datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator, Protocol +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 RevisionInstance(InstanceResource): + + + """ + :ivar revisions: Array of observation revisions ordered chronologically descending by update time (newest first). + :ivar meta: + """ + + def __init__(self, version: Version, payload:Dict[str, Any], store_id: Optional[str] = None, profile_id: Optional[str] = None, observation_id: Optional[str] = None): + super().__init__(version) + + + self.revisions: Optional[List[Dict[str, object]]] = payload.get("revisions") + self.meta: Optional[str] = payload.get("meta") + + + self._solution = { + "store_id": store_id or self.store_id, + "profile_id": profile_id or self.profile_id, + "observation_id": observation_id or self.observation_id, + } + self._context: Optional[RevisionContext] = None + + @property + def _proxy(self) -> "RevisionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RevisionContext for this RevisionInstance + """ + if self._context is None: + self._context = RevisionContext(self._version, store_id=self._solution['store_id'], profile_id=self._solution['profile_id'], observation_id=self._solution['observation_id'],) + return self._context + + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) + return ''.format(context) + +class RevisionContext(InstanceContext): + + def __init__(self, version: Version, store_id: str, profile_id: str, observation_id: str): + """ + Initialize the RevisionContext + + :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 __repr__(self) -> str: + """ + 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) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + + + + +class RevisionList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the RevisionList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + + + + + + def get(self, store_id: str, profile_id: str, observation_id: str) -> RevisionContext: + """ + Constructs a RevisionContext + + :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. + """ + return RevisionContext(self._version, store_id=store_id, profile_id=profile_id, observation_id=observation_id) + + def __call__(self, store_id: str, profile_id: str, observation_id: str) -> RevisionContext: + """ + Constructs a RevisionContext + + :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. + """ + return RevisionContext(self._version, store_id=store_id, profile_id=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/store.py b/twilio/rest/memory/v1/store.py new file mode 100644 index 000000000..d023c38cc --- /dev/null +++ b/twilio/rest/memory/v1/store.py @@ -0,0 +1,1270 @@ +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 datetime import date, datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator, Protocol +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 ResponseResource(Protocol): + pass + +''' +Nested response model for Meta +''' +class Meta: + def __init__(self,key: str, page_size: int, next_token: str, previous_token: str): + self.key = key + self.page_size = page_size + self.next_token = next_token + self.previous_token = previous_token + + + +''' +Nested response model for ServiceRequest +''' +class ServiceRequest: + def __init__(self,display_name: str, description: str): + self.display_name = display_name + self.description = description + + + +''' +Nested response model for UpdateStoreRequest +''' +class UpdateStoreRequest: + def __init__(self,display_name: str, description: str): + self.display_name = display_name + self.description = description + + + + + +""" +Response model for ServiceList operations +""" +class ServiceListResource: + def __init__(self,stores: List[str], meta: Meta): + """ + Initialize the ServiceListResource + :param stores: List of Memory Store IDs associated with the Twilio account. + :param meta: + + """ + self.stores = stores + self.meta = meta + + +""" +Response model for Store operations +""" +class StoreResource: + def __init__(self,display_name: str, description: str, id: str, status: str, intelligence_service_id: str, version: int): + """ + Initialize the StoreResource + :param 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. + :param description: A human readable description of this resource, up to 128 characters. + :param id: The unique identifier for the Memory Store + :param 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. + :param intelligence_service_id: The ID of the associated intelligence service that was provisioned for memory extraction. + :param version: The current version number of the Memory Store. Incremented on each successful update. + + """ + self.display_name = display_name + self.description = description + self.id = id + self.status = status + self.intelligence_service_id = intelligence_service_id + self.version = version + + + + +class StoreInstance(InstanceResource): + + 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("page_size") + self.next_token: Optional[str] = payload.get("next_token") + self.previous_token: Optional[str] = payload.get("previous_token") + + def to_dict(self): + return { + + "": self.key, + "": self.page_size, + "": self.next_token, + "": self.previous_token, + } + + 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("display_name") + self.description: Optional[str] = payload.get("description") + + def to_dict(self): + return { + + "display_name": self.display_name, + "description": self.description, + } + + class UpdateStoreRequest(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("display_name") + self.description: Optional[str] = payload.get("description") + + def to_dict(self): + return { + + "display_name": self.display_name, + "description": self.description, + } + + + + """ + :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.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + self.id: Optional[str] = payload.get("id") + self.status: Optional[str] = payload.get("status") + self.intelligence_service_id: Optional[str] = payload.get("intelligenceServiceId") + self.version: Optional[int] = deserialize.integer(payload.get("version")) + + + self._solution = { + "store_id": store_id or self.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 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 update(self, if_match: Union[str, object]=values.unset, prefer: Union[str, object]=values.unset, update_store_request: Union[UpdateStoreRequest, object]=values.unset) -> "StoreInstance": + """ + Update 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 one provided, preventing accidental overwrites and responding with 412 Precondition Failed if they don't match. + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + :param update_store_request: + + :returns: The updated StoreInstance + """ + return self._proxy.update(if_match=if_match, prefer=prefer, update_store_request=update_store_request, ) + + async def update_async(self, if_match: Union[str, object]=values.unset, prefer: Union[str, object]=values.unset, update_store_request: Union[UpdateStoreRequest, object]=values.unset) -> "StoreInstance": + """ + Asynchronous coroutine to update 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 one provided, preventing accidental overwrites and responding with 412 Precondition Failed if they don't match. + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + :param update_store_request: + + :returns: The updated StoreInstance + """ + return await self._proxy.update_async(if_match=if_match, prefer=prefer, update_store_request=update_store_request, ) + + def update_with_http_info(self, if_match: Union[str, object]=values.unset, prefer: Union[str, object]=values.unset, update_store_request: Union[UpdateStoreRequest, object]=values.unset) -> ApiResponse: + """ + Update the StoreInstance with HTTP info + + :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 one provided, preventing accidental overwrites and responding with 412 Precondition Failed if they don't match. + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + :param update_store_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info(if_match=if_match, prefer=prefer, update_store_request=update_store_request, ) + + async def update_with_http_info_async(self, if_match: Union[str, object]=values.unset, prefer: Union[str, object]=values.unset, update_store_request: Union[UpdateStoreRequest, object]=values.unset) -> ApiResponse: + """ + Asynchronous coroutine to update the StoreInstance with HTTP info + + :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 one provided, preventing accidental overwrites and responding with 412 Precondition Failed if they don't match. + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + :param update_store_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async(if_match=if_match, prefer=prefer, update_store_request=update_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): + + 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("page_size") + self.next_token: Optional[str] = payload.get("next_token") + self.previous_token: Optional[str] = payload.get("previous_token") + + def to_dict(self): + return { + + "": self.key, + "": self.page_size, + "": self.next_token, + "": self.previous_token, + } + + 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("display_name") + self.description: Optional[str] = payload.get("description") + + def to_dict(self): + return { + + "display_name": self.display_name, + "description": self.description, + } + + class UpdateStoreRequest(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("display_name") + self.description: Optional[str] = payload.get("description") + + def to_dict(self): + return { + + "display_name": self.display_name, + "description": self.description, + } + + + 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 _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 _update(self, if_match: Union[str, object]=values.unset, prefer: Union[str, object]=values.unset, update_store_request: Union[UpdateStoreRequest, object]=values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = update_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 + + if not (prefer is values.unset or (isinstance(prefer, str) and not prefer)): + headers['Prefer'] = prefer + + 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, if_match: Union[str, object]=values.unset, prefer: Union[str, object]=values.unset, update_store_request: Union[UpdateStoreRequest, object]=values.unset) -> StoreInstance: + """ + Update 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 one provided, preventing accidental overwrites and responding with 412 Precondition Failed if they don't match. + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + :param update_store_request: + + :returns: The updated StoreInstance + """ + payload, _, _ = self._update(if_match=if_match, prefer=prefer, update_store_request=update_store_request) + return StoreInstance( + self._version, + payload, + store_id=self._solution['store_id'] + ) + + def update_with_http_info(self, if_match: Union[str, object]=values.unset, prefer: Union[str, object]=values.unset, update_store_request: Union[UpdateStoreRequest, object]=values.unset) -> ApiResponse: + """ + Update 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 one provided, preventing accidental overwrites and responding with 412 Precondition Failed if they don't match. + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + :param update_store_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(if_match=if_match, prefer=prefer, update_store_request=update_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 _update_async(self, if_match: Union[str, object]=values.unset, prefer: Union[str, object]=values.unset, update_store_request: Union[UpdateStoreRequest, object]=values.unset) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = update_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 + + + if not (prefer is values.unset or (isinstance(prefer, str) and not prefer)): + headers['Prefer'] = prefer + + + 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, if_match: Union[str, object]=values.unset, prefer: Union[str, object]=values.unset, update_store_request: Union[UpdateStoreRequest, object]=values.unset) -> StoreInstance: + """ + Asynchronous coroutine to update 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 one provided, preventing accidental overwrites and responding with 412 Precondition Failed if they don't match. + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + :param update_store_request: + + :returns: The updated StoreInstance + """ + payload, _, _ = await self._update_async(if_match=if_match, prefer=prefer, update_store_request=update_store_request) + return StoreInstance( + self._version, + payload, + store_id=self._solution['store_id'] + ) + + async def update_with_http_info_async(self, if_match: Union[str, object]=values.unset, prefer: Union[str, object]=values.unset, update_store_request: Union[UpdateStoreRequest, object]=values.unset) -> ApiResponse: + """ + Asynchronous coroutine to update 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 one provided, preventing accidental overwrites and responding with 412 Precondition Failed if they don't match. + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + :param update_store_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(if_match=if_match, prefer=prefer, update_store_request=update_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: Dict[str, Any]) -> StoreInstance: + """ + Build an instance of StoreInstance + + :param payload: Payload response from the API + """ + return StoreInstance(self._version, payload) + + 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("page_size") + self.next_token: Optional[str] = payload.get("next_token") + self.previous_token: Optional[str] = payload.get("previous_token") + + def to_dict(self): + return { + + "": self.key, + "": self.page_size, + "": self.next_token, + "": self.previous_token, + } + + 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("display_name") + self.description: Optional[str] = payload.get("description") + + def to_dict(self): + return { + + "display_name": self.display_name, + "description": self.description, + } + + class UpdateStoreRequest(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("display_name") + self.description: Optional[str] = payload.get("description") + + def to_dict(self): + return { + + "display_name": 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[StoreInstance]: + """ + Lists StoreInstance 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[StoreInstance]: + """ + Asynchronously lists StoreInstance 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 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, + + page_token: Union[str, 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 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 000000000..c090fbafa --- /dev/null +++ b/twilio/rest/memory/v1/trait.py @@ -0,0 +1,173 @@ +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 datetime import date, datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator, Protocol +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 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: Optional[str] = None, profile_id: Optional[str] = None): + 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")) + + + self._solution = { + "store_id": store_id or self.store_id, + "profile_id": profile_id or self.profile_id, + } + self._context: Optional[TraitContext] = None + + @property + def _proxy(self) -> "TraitContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TraitContext for this TraitInstance + """ + if self._context is None: + self._context = TraitContext(self._version, store_id=self._solution['store_id'], profile_id=self._solution['profile_id'],) + return self._context + + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) + return ''.format(context) + +class TraitContext(InstanceContext): + + def __init__(self, version: Version, store_id: str, profile_id: str): + """ + Initialize the TraitContext + + :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 __repr__(self) -> str: + """ + 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) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + + + + +class TraitList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the TraitList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + + + + + + def get(self, store_id: str, profile_id: str) -> TraitContext: + """ + Constructs a TraitContext + + :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. + """ + return TraitContext(self._version, store_id=store_id, profile_id=profile_id) + + def __call__(self, store_id: str, profile_id: str) -> TraitContext: + """ + Constructs a TraitContext + + :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. + """ + return TraitContext(self._version, store_id=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/trait_group.py b/twilio/rest/memory/v1/trait_group.py new file mode 100644 index 000000000..6814991b2 --- /dev/null +++ b/twilio/rest/memory/v1/trait_group.py @@ -0,0 +1,1360 @@ +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 datetime import date, datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator, Protocol +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 ResponseResource(Protocol): + pass + +''' +Nested response model for Meta +''' +class Meta: + def __init__(self,key: str, page_size: int, next_token: str, previous_token: str): + self.key = key + self.page_size = page_size + self.next_token = next_token + self.previous_token = previous_token + + + +''' +Nested response model for TraitDefinition +''' +class TraitDefinition: + def __init__(self,display_name: str, data_type: str, description: str, id_type_promotion: str): + self.display_name = display_name + self.data_type = data_type + self.description = description + self.id_type_promotion = id_type_promotion + + + +''' +Nested response model for TraitGroup +''' +class TraitGroup: + def __init__(self,display_name: str, description: str, traits: Dict[str, TraitGroupCoreTraitsValue], version: int): + self.display_name = display_name + self.description = description + self.traits = traits + self.version = version + + + +''' +Nested response model for TraitGroupCoreTraitsValue +''' +class TraitGroupCoreTraitsValue: + def __init__(self,display_name: str, data_type: str, description: str, validation_rule: ValidationRule, id_type_promotion: str): + self.display_name = display_name + self.data_type = data_type + self.description = description + self.validation_rule = validation_rule + self.id_type_promotion = id_type_promotion + + + +''' +Nested response model for TraitGroupRequest +''' +class TraitGroupRequest: + def __init__(self,display_name: str, description: str, traits: Dict[str, TraitGroupCoreTraitsValue]): + self.display_name = display_name + self.description = description + self.traits = traits + + + +''' +Nested response model for UpdateTraitGroupRequest +''' +class UpdateTraitGroupRequest: + def __init__(self,description: str, traits: Dict[str, TraitDefinition]): + self.description = description + self.traits = traits + + + +''' +Nested response model for ValidationRule +''' +class ValidationRule: + def __init__(self,pattern: str, min_length: int, max_length: int, rule_type: str, min: float, max: float, min_items: int, max_items: int): + self.pattern = pattern + self.min_length = min_length + self.max_length = max_length + self.rule_type = rule_type + self.min = min + self.max = max + self.min_items = min_items + self.max_items = max_items + + + + + +""" +Response model for DeleteTraitGroup_202_response operations +""" +class DeleteTraitGroup_202_responseResource: + def __init__(self,message: str): + """ + Initialize the DeleteTraitGroup_202_responseResource + :param message: + + """ + self.message = message + + +""" +Response model for CreateTraitGroup_201_response operations +""" +class CreateTraitGroup_201_responseResource: + def __init__(self,trait_group: str, meta: str): + """ + Initialize the CreateTraitGroup_201_responseResource + :param trait_group: + :param meta: + + """ + self.trait_group = trait_group + self.meta = meta + + +""" +Response model for TraitGroup operations +""" +class TraitGroupResource: + def __init__(self,display_name: str, description: str, traits: Dict[str, TraitGroupCoreTraitsValue], version: int): + """ + Initialize the TraitGroupResource + :param display_name: Provides a unique and addressable name to be assigned to this Trait Group + :param description: description of the Trait Group + :param 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. + :param version: The current version number of the Trait Group. Incremented on each successful update. + + """ + self.display_name = display_name + self.description = description + self.traits = traits + self.version = version + + + + +class TraitGroupInstance(InstanceResource): + + class TraitDefinition(object): + """ + :ivar display_name: Display name of the Trait, which is unique within the Trait Group. Trait names are normalized to lowerCamelCase naming conventions and can include letters, numbers, underscores, hyphens, and periods. They must start with a letter. + :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.display_name: Optional[str] = payload.get("display_name") + self.data_type: Optional[str] = payload.get("data_type") + self.description: Optional[str] = payload.get("description") + self.id_type_promotion: Optional[str] = payload.get("id_type_promotion") + + def to_dict(self): + return { + + "": self.display_name, + "": self.data_type, + "": self.description, + "": self.id_type_promotion, + } + + class TraitGroupCoreTraitsValue(object): + """ + :ivar display_name: Display name of the Trait, which is unique within the Trait Group. Trait names are normalized to lowerCamelCase naming conventions and can include letters, numbers, underscores, hyphens, and periods. They must start with a letter. + :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.display_name: Optional[str] = payload.get("display_name") + self.data_type: Optional[str] = payload.get("data_type") + self.description: Optional[str] = payload.get("description") + self.validation_rule: Optional[ValidationRule] = payload.get("validation_rule") + self.id_type_promotion: Optional[str] = payload.get("id_type_promotion") + + def to_dict(self): + return { + + "": self.display_name, + "": self.data_type, + "": self.description, + "": self.validation_rule.to_dict() if self.validation_rule is not None else None , + "": 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("display_name") + self.description: Optional[str] = payload.get("description") + self.traits: Optional[Dict[str, TraitGroupCoreTraitsValue]] = payload.get("traits") + + def to_dict(self): + return { + + "display_name": self.display_name, + "description": self.description, + "traits": [traits.to_dict() for traits in self.traits] if self.traits is not None else None, + } + + class UpdateTraitGroupRequest(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": [traits.to_dict() for traits in self.traits] 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("min_length") + self.max_length: Optional[int] = payload.get("max_length") + self.rule_type: Optional[str] = payload.get("rule_type") + self.min: Optional[float] = payload.get("min") + self.max: Optional[float] = payload.get("max") + self.min_items: Optional[int] = payload.get("min_items") + self.max_items: Optional[int] = payload.get("max_items") + + def to_dict(self): + return { + + "": self.pattern, + "": self.min_length, + "": self.max_length, + "": self.rule_type, + "": self.min, + "": self.max, + "": self.min_items, + "": self.max_items, + } + + + + """ + :ivar trait_group: + :ivar meta: + """ + + def __init__(self, version: Version, payload:ResponseResource, store_id: Optional[str] = None, trait_group_name: Optional[str] = None): + super().__init__(version) + + + self.trait_group: Optional[str] = payload.get("traitGroup") + self.meta: Optional[str] = payload.get("meta") + + + self._solution = { + "store_id": store_id or self.store_id, + "trait_group_name": trait_group_name or self.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 create(self, prefer: Union[str, object]=values.unset, trait_group_request: Union[TraitGroupRequest, object]=values.unset) -> "TraitGroupInstance": + """ + Create the TraitGroupInstance + + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + :param trait_group_request: + + :returns: The created TraitGroupInstance + """ + return self._proxy.create(prefer=prefer, trait_group_request=trait_group_request, ) + async def create_async(self, prefer: Union[str, object]=values.unset, trait_group_request: Union[TraitGroupRequest, object]=values.unset) -> "TraitGroupInstance": + """ + Asynchronous coroutine to create the TraitGroupInstance + + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + :param trait_group_request: + + :returns: The created TraitGroupInstance + """ + return await self._proxy.create_async(prefer=prefer, trait_group_request=trait_group_request, ) + + def create_with_http_info(self, prefer: Union[str, object]=values.unset, trait_group_request: Union[TraitGroupRequest, object]=values.unset) -> ApiResponse: + """ + Create the TraitGroupInstance with HTTP info + + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + :param trait_group_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info(prefer=prefer, trait_group_request=trait_group_request, ) + + async def create_with_http_info_async(self, prefer: Union[str, object]=values.unset, trait_group_request: Union[TraitGroupRequest, object]=values.unset) -> ApiResponse: + """ + Asynchronous coroutine to create the TraitGroupInstance with HTTP info + + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + :param trait_group_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_async(prefer=prefer, trait_group_request=trait_group_request, ) + + + def delete(self, prefer: Union[str, object]=values.unset) -> bool: + """ + Deletes the TraitGroupInstance + + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete(prefer=prefer, ) + async def delete_async(self, prefer: Union[str, object]=values.unset) -> bool: + """ + Asynchronous coroutine that deletes the TraitGroupInstance + + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async(prefer=prefer, ) + + def delete_with_http_info(self, prefer: Union[str, object]=values.unset) -> ApiResponse: + """ + Deletes the TraitGroupInstance with HTTP info + + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info(prefer=prefer, ) + + async def delete_with_http_info_async(self, prefer: Union[str, object]=values.unset) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TraitGroupInstance with HTTP info + + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async(prefer=prefer, ) + + + 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 update(self, if_match: Union[str, object]=values.unset, prefer: Union[str, object]=values.unset, update_trait_group_request: Union[UpdateTraitGroupRequest, object]=values.unset) -> "TraitGroupInstance": + """ + Update 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 one provided, preventing accidental overwrites and responding with 412 Precondition Failed if they don't match. + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + :param update_trait_group_request: + + :returns: The updated TraitGroupInstance + """ + return self._proxy.update(if_match=if_match, prefer=prefer, update_trait_group_request=update_trait_group_request, ) + + async def update_async(self, if_match: Union[str, object]=values.unset, prefer: Union[str, object]=values.unset, update_trait_group_request: Union[UpdateTraitGroupRequest, object]=values.unset) -> "TraitGroupInstance": + """ + Asynchronous coroutine to update 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 one provided, preventing accidental overwrites and responding with 412 Precondition Failed if they don't match. + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + :param update_trait_group_request: + + :returns: The updated TraitGroupInstance + """ + return await self._proxy.update_async(if_match=if_match, prefer=prefer, update_trait_group_request=update_trait_group_request, ) + + def update_with_http_info(self, if_match: Union[str, object]=values.unset, prefer: Union[str, object]=values.unset, update_trait_group_request: Union[UpdateTraitGroupRequest, object]=values.unset) -> ApiResponse: + """ + Update the TraitGroupInstance with HTTP info + + :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 one provided, preventing accidental overwrites and responding with 412 Precondition Failed if they don't match. + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + :param update_trait_group_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info(if_match=if_match, prefer=prefer, update_trait_group_request=update_trait_group_request, ) + + async def update_with_http_info_async(self, if_match: Union[str, object]=values.unset, prefer: Union[str, object]=values.unset, update_trait_group_request: Union[UpdateTraitGroupRequest, object]=values.unset) -> ApiResponse: + """ + Asynchronous coroutine to update the TraitGroupInstance with HTTP info + + :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 one provided, preventing accidental overwrites and responding with 412 Precondition Failed if they don't match. + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + :param update_trait_group_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async(if_match=if_match, prefer=prefer, update_trait_group_request=update_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): + + class TraitDefinition(object): + """ + :ivar display_name: Display name of the Trait, which is unique within the Trait Group. Trait names are normalized to lowerCamelCase naming conventions and can include letters, numbers, underscores, hyphens, and periods. They must start with a letter. + :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.display_name: Optional[str] = payload.get("display_name") + self.data_type: Optional[str] = payload.get("data_type") + self.description: Optional[str] = payload.get("description") + self.id_type_promotion: Optional[str] = payload.get("id_type_promotion") + + def to_dict(self): + return { + + "": self.display_name, + "": self.data_type, + "": self.description, + "": self.id_type_promotion, + } + + class TraitGroupCoreTraitsValue(object): + """ + :ivar display_name: Display name of the Trait, which is unique within the Trait Group. Trait names are normalized to lowerCamelCase naming conventions and can include letters, numbers, underscores, hyphens, and periods. They must start with a letter. + :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.display_name: Optional[str] = payload.get("display_name") + self.data_type: Optional[str] = payload.get("data_type") + self.description: Optional[str] = payload.get("description") + self.validation_rule: Optional[ValidationRule] = payload.get("validation_rule") + self.id_type_promotion: Optional[str] = payload.get("id_type_promotion") + + def to_dict(self): + return { + + "": self.display_name, + "": self.data_type, + "": self.description, + "": self.validation_rule.to_dict() if self.validation_rule is not None else None , + "": 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("display_name") + self.description: Optional[str] = payload.get("description") + self.traits: Optional[Dict[str, TraitGroupCoreTraitsValue]] = payload.get("traits") + + def to_dict(self): + return { + + "display_name": self.display_name, + "description": self.description, + "traits": [traits.to_dict() for traits in self.traits] if self.traits is not None else None, + } + + class UpdateTraitGroupRequest(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": [traits.to_dict() for traits in self.traits] 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("min_length") + self.max_length: Optional[int] = payload.get("max_length") + self.rule_type: Optional[str] = payload.get("rule_type") + self.min: Optional[float] = payload.get("min") + self.max: Optional[float] = payload.get("max") + self.min_items: Optional[int] = payload.get("min_items") + self.max_items: Optional[int] = payload.get("max_items") + + def to_dict(self): + return { + + "": self.pattern, + "": self.min_length, + "": self.max_length, + "": self.rule_type, + "": self.min, + "": self.max, + "": self.min_items, + "": self.max_items, + } + + + 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 _create(self, prefer: Union[str, object]=values.unset, 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({}) + + + if not (prefer is values.unset or (isinstance(prefer, str) and not prefer)): + headers['Prefer'] = prefer + + 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, prefer: Union[str, object]=values.unset, trait_group_request: Union[TraitGroupRequest, object]=values.unset) -> TraitGroupInstance: + """ + Create the TraitGroupInstance + + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + :param trait_group_request: + + :returns: The created TraitGroupInstance + """ + payload, _, _ = self._create(prefer=prefer, trait_group_request=trait_group_request) + return TraitGroupInstance( + self._version, + payload, + store_id=self._solution['store_id'], + trait_group_name=self._solution['trait_group_name'] + ) + + def create_with_http_info(self, prefer: Union[str, object]=values.unset, trait_group_request: Union[TraitGroupRequest, object]=values.unset) -> ApiResponse: + """ + Create the TraitGroupInstance and return response metadata + + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + :param trait_group_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(prefer=prefer, trait_group_request=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 _create_async(self, prefer: Union[str, object]=values.unset, 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({}) + + + if not (prefer is values.unset or (isinstance(prefer, str) and not prefer)): + headers['Prefer'] = prefer + + 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, prefer: Union[str, object]=values.unset, trait_group_request: Union[TraitGroupRequest, object]=values.unset) -> TraitGroupInstance: + """ + Asynchronous coroutine to create the TraitGroupInstance + + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + :param trait_group_request: + + :returns: The created TraitGroupInstance + """ + payload, _, _ = await self._create_async(prefer=prefer, trait_group_request=trait_group_request) + return TraitGroupInstance( + self._version, + payload, + store_id=self._solution['store_id'], + trait_group_name=self._solution['trait_group_name'] + ) + + async def create_with_http_info_async(self, prefer: Union[str, object]=values.unset, trait_group_request: Union[TraitGroupRequest, object]=values.unset) -> ApiResponse: + """ + Asynchronous coroutine to create the TraitGroupInstance and return response metadata + + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + :param trait_group_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(prefer=prefer, trait_group_request=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 _delete(self, prefer: Union[str, object]=values.unset) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of({'Prefer': prefer, }) + + + + headers = values.of({}) + + + + headers["Accept"] = "application/json" + + return self._version.delete_with_response_info(method='DELETE', uri=self._uri, headers=headers) + + def delete(self, prefer: Union[str, object]=values.unset) -> bool: + """ + Deletes the TraitGroupInstance + + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete(prefer=prefer) + return success + + def delete_with_http_info(self, prefer: Union[str, object]=values.unset) -> ApiResponse: + """ + Deletes the TraitGroupInstance and return response metadata + + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete(prefer=prefer) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self, prefer: Union[str, object]=values.unset) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of({'Prefer': prefer, }) + + + 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, prefer: Union[str, object]=values.unset) -> bool: + """ + Asynchronous coroutine that deletes the TraitGroupInstance + + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async(prefer=prefer) + return success + + async def delete_with_http_info_async(self, prefer: Union[str, object]=values.unset) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TraitGroupInstance and return response metadata + + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async(prefer=prefer) + 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 _update(self, if_match: Union[str, object]=values.unset, prefer: Union[str, object]=values.unset, update_trait_group_request: Union[UpdateTraitGroupRequest, object]=values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = update_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 + + if not (prefer is values.unset or (isinstance(prefer, str) and not prefer)): + headers['Prefer'] = prefer + + 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, if_match: Union[str, object]=values.unset, prefer: Union[str, object]=values.unset, update_trait_group_request: Union[UpdateTraitGroupRequest, object]=values.unset) -> TraitGroupInstance: + """ + Update 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 one provided, preventing accidental overwrites and responding with 412 Precondition Failed if they don't match. + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + :param update_trait_group_request: + + :returns: The updated TraitGroupInstance + """ + payload, _, _ = self._update(if_match=if_match, prefer=prefer, update_trait_group_request=update_trait_group_request) + return TraitGroupInstance( + self._version, + payload, + store_id=self._solution['store_id'], + trait_group_name=self._solution['trait_group_name'] + ) + + def update_with_http_info(self, if_match: Union[str, object]=values.unset, prefer: Union[str, object]=values.unset, update_trait_group_request: Union[UpdateTraitGroupRequest, object]=values.unset) -> ApiResponse: + """ + Update 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 one provided, preventing accidental overwrites and responding with 412 Precondition Failed if they don't match. + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + :param update_trait_group_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(if_match=if_match, prefer=prefer, update_trait_group_request=update_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 _update_async(self, if_match: Union[str, object]=values.unset, prefer: Union[str, object]=values.unset, update_trait_group_request: Union[UpdateTraitGroupRequest, object]=values.unset) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = update_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 + + + if not (prefer is values.unset or (isinstance(prefer, str) and not prefer)): + headers['Prefer'] = prefer + + + 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, if_match: Union[str, object]=values.unset, prefer: Union[str, object]=values.unset, update_trait_group_request: Union[UpdateTraitGroupRequest, object]=values.unset) -> TraitGroupInstance: + """ + Asynchronous coroutine to update 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 one provided, preventing accidental overwrites and responding with 412 Precondition Failed if they don't match. + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + :param update_trait_group_request: + + :returns: The updated TraitGroupInstance + """ + payload, _, _ = await self._update_async(if_match=if_match, prefer=prefer, update_trait_group_request=update_trait_group_request) + return TraitGroupInstance( + self._version, + payload, + store_id=self._solution['store_id'], + trait_group_name=self._solution['trait_group_name'] + ) + + async def update_with_http_info_async(self, if_match: Union[str, object]=values.unset, prefer: Union[str, object]=values.unset, update_trait_group_request: Union[UpdateTraitGroupRequest, object]=values.unset) -> ApiResponse: + """ + Asynchronous coroutine to update 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 one provided, preventing accidental overwrites and responding with 412 Precondition Failed if they don't match. + :param prefer: Allows specifying a preference for waiting for completion of the operation before responding. Set **respond-async; wait=X**, where **X** is the number of seconds for the server to wait. The operation will return a 2xx success code if it completes within the specified wait time, otherwise a 202 Accepted is returned and processing continues asynchronously. + :param update_trait_group_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(if_match=if_match, prefer=prefer, update_trait_group_request=update_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) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + + + + + + +class TraitGroupList(ListResource): + + class TraitDefinition(object): + """ + :ivar display_name: Display name of the Trait, which is unique within the Trait Group. Trait names are normalized to lowerCamelCase naming conventions and can include letters, numbers, underscores, hyphens, and periods. They must start with a letter. + :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.display_name: Optional[str] = payload.get("display_name") + self.data_type: Optional[str] = payload.get("data_type") + self.description: Optional[str] = payload.get("description") + self.id_type_promotion: Optional[str] = payload.get("id_type_promotion") + + def to_dict(self): + return { + + "": self.display_name, + "": self.data_type, + "": self.description, + "": self.id_type_promotion, + } + + class TraitGroupCoreTraitsValue(object): + """ + :ivar display_name: Display name of the Trait, which is unique within the Trait Group. Trait names are normalized to lowerCamelCase naming conventions and can include letters, numbers, underscores, hyphens, and periods. They must start with a letter. + :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.display_name: Optional[str] = payload.get("display_name") + self.data_type: Optional[str] = payload.get("data_type") + self.description: Optional[str] = payload.get("description") + self.validation_rule: Optional[ValidationRule] = payload.get("validation_rule") + self.id_type_promotion: Optional[str] = payload.get("id_type_promotion") + + def to_dict(self): + return { + + "": self.display_name, + "": self.data_type, + "": self.description, + "": self.validation_rule.to_dict() if self.validation_rule is not None else None , + "": 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("display_name") + self.description: Optional[str] = payload.get("description") + self.traits: Optional[Dict[str, TraitGroupCoreTraitsValue]] = payload.get("traits") + + def to_dict(self): + return { + + "display_name": self.display_name, + "description": self.description, + "traits": [traits.to_dict() for traits in self.traits] if self.traits is not None else None, + } + + class UpdateTraitGroupRequest(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": [traits.to_dict() for traits in self.traits] 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("min_length") + self.max_length: Optional[int] = payload.get("max_length") + self.rule_type: Optional[str] = payload.get("rule_type") + self.min: Optional[float] = payload.get("min") + self.max: Optional[float] = payload.get("max") + self.min_items: Optional[int] = payload.get("min_items") + self.max_items: Optional[int] = payload.get("max_items") + + def to_dict(self): + return { + + "": self.pattern, + "": self.min_length, + "": self.max_length, + "": self.rule_type, + "": self.min, + "": self.max, + "": self.min_items, + "": self.max_items, + } + + + def __init__(self, version: Version): + """ + Initialize the TraitGroupList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + + + + + + def get(self, store_id: str, trait_group_name: str) -> TraitGroupContext: + """ + Constructs a TraitGroupContext + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + :param trait_group_name: A unique Name of the TraitGroup + """ + return TraitGroupContext(self._version, store_id=store_id, trait_group_name=trait_group_name) + + def __call__(self, store_id: str, trait_group_name: str) -> TraitGroupContext: + """ + Constructs a TraitGroupContext + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + :param trait_group_name: A unique Name of the TraitGroup + """ + return TraitGroupContext(self._version, store_id=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/monitor/v2/__init__.py b/twilio/rest/monitor/v2/__init__.py new file mode 100644 index 000000000..699b46898 --- /dev/null +++ b/twilio/rest/monitor/v2/__init__.py @@ -0,0 +1,51 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Alarms + Manages Twilio Alarms + + NOTE: This 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.v2.alarm import AlarmList +from twilio.rest.monitor.v2.status import StatusList + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of Monitor + + :param domain: The Twilio.monitor domain + """ + super().__init__(domain, "v2") + self._alarms: Optional[AlarmList] = None + self._status: Optional[StatusList] = None + + @property + def alarms(self) -> AlarmList: + if self._alarms is None: + self._alarms = AlarmList(self) + return self._alarms + + @property + def status(self) -> StatusList: + if self._status is None: + self._status = StatusList(self) + return self._status + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/monitor/v2/alarm.py b/twilio/rest/monitor/v2/alarm.py new file mode 100644 index 000000000..8779a6ade --- /dev/null +++ b/twilio/rest/monitor/v2/alarm.py @@ -0,0 +1,1240 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Alarms + Manages Twilio Alarms + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + + +from datetime import date, datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator, Protocol +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 AlarmInstance(InstanceResource): + + class MonitorV2AlarmCreateObject(object): + """ + :ivar friendly_name: Friendly name for alarm + :ivar query_type: + :ivar query: Value to query for + :ivar trigger_value: Threshold to send customer alarm notification + :ivar time_window: + :ivar email: Email notifications to send + :ivar webhook: Webhook notification to send + :ivar console_indicator: Whether to send console notifications + :ivar description: Description for the alarm. + :ivar enabled: Is alarm enbled? Default is true. + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.query_type: Optional["AlarmInstance.QueryType"] = payload.get("query_type") + self.query: Optional[str] = payload.get("query") + self.trigger_value: Optional[int] = payload.get("trigger_value") + self.time_window: Optional["AlarmInstance.TimeWindow"] = payload.get("time_window") + self.email: Optional[List[str]] = payload.get("email") + self.webhook: Optional[str] = payload.get("webhook") + self.console_indicator: Optional[bool] = payload.get("console_indicator") + self.description: Optional[str] = payload.get("description") + self.enabled: Optional[bool] = payload.get("enabled") + + def to_dict(self): + return { + + "friendly_name": self.friendly_name, + "query_type": self.query_type, + "query": self.query, + "trigger_value": self.trigger_value, + "time_window": self.time_window, + "email": self.email, + "webhook": self.webhook, + "console_indicator": self.console_indicator, + "description": self.description, + "enabled": self.enabled, + } + + + + class QueryType(object): + ERROR_CODE = "ERROR_CODE" + LOG_LEVEL = "LOG_LEVEL" + ALL = "ALL" + + class TimeWindow(object): + FIVE_MINS = "FIVE_MINS" + FIFTEEN_MINS = "FIFTEEN_MINS" + ONE_HOUR = "ONE_HOUR" + TWELVE_HOURS = "TWELVE_HOURS" + ONE_DAY = "ONE_DAY" + + """ + :ivar sid: + :ivar message: Error message + :ivar code: Twilio error code + :ivar user_error: Indicates if it was a user error + :ivar http_status_code: Http error code returned + :ivar params: + :ivar more_info: More information link + :ivar status: HTTP status code + :ivar friendly_name: Friendly name for alarm + :ivar query_type: + :ivar query: Value to query for + :ivar trigger_value: Threshold to send customer alarm notification + :ivar time_window: + :ivar email: Email notifications to send + :ivar webhook: Webhook notification to send + :ivar console_indicator: Whether to send console notifications + :ivar description: Description for the alarm. + :ivar enabled: Is alarm enbled? Default is true. + :ivar product: Product the alarm is related to. + :ivar alert_config_sid: Sid for the alarm + :ivar date_updated: The date and time in UTC when the alarm was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format + :ivar date_created: The date and time in UTC when the alarm was created 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.sid: Optional[str] = payload.get("sid") + self.message: Optional[str] = payload.get("message") + self.code: Optional[int] = deserialize.integer(payload.get("code")) + self.user_error: Optional[bool] = payload.get("user_error") + self.http_status_code: Optional[int] = deserialize.integer(payload.get("http_status_code")) + self.params: Optional[Dict[str, str]] = payload.get("params") + self.more_info: Optional[str] = payload.get("more_info") + self.status: Optional[int] = deserialize.integer(payload.get("status")) + self.friendly_name: Optional[str] = payload.get("friendlyName") + self.query_type: Optional[str] = payload.get("queryType") + self.query: Optional[str] = payload.get("query") + self.trigger_value: Optional[int] = deserialize.integer(payload.get("triggerValue")) + self.time_window: Optional[str] = payload.get("timeWindow") + self.email: Optional[List[str]] = payload.get("email") + self.webhook: Optional[str] = payload.get("webhook") + self.console_indicator: Optional[bool] = payload.get("consoleIndicator") + self.description: Optional[str] = payload.get("description") + self.enabled: Optional[bool] = payload.get("enabled") + self.product: Optional[str] = payload.get("product") + self.alert_config_sid: Optional[str] = payload.get("alertConfigSid") + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime(payload.get("dateUpdated")) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime(payload.get("dateCreated")) + + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[AlarmContext] = None + + @property + def _proxy(self) -> "AlarmContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AlarmContext for this AlarmInstance + """ + if self._context is None: + self._context = AlarmContext(self._version, sid=self._solution['sid'],) + return self._context + + + def delete(self) -> bool: + """ + Deletes the AlarmInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AlarmInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AlarmInstance 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 AlarmInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + + def fetch(self) -> "AlarmInstance": + """ + Fetch the AlarmInstance + + + :returns: The fetched AlarmInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AlarmInstance": + """ + Asynchronous coroutine to fetch the AlarmInstance + + + :returns: The fetched AlarmInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AlarmInstance 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 AlarmInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + + def update(self, monitor_v2_alarm_create_object: MonitorV2AlarmCreateObject) -> "AlarmInstance": + """ + Update the AlarmInstance + + :param monitor_v2_alarm_create_object: + + :returns: The updated AlarmInstance + """ + return self._proxy.update(monitor_v2_alarm_create_object=monitor_v2_alarm_create_object, ) + + async def update_async(self, monitor_v2_alarm_create_object: MonitorV2AlarmCreateObject) -> "AlarmInstance": + """ + Asynchronous coroutine to update the AlarmInstance + + :param monitor_v2_alarm_create_object: + + :returns: The updated AlarmInstance + """ + return await self._proxy.update_async(monitor_v2_alarm_create_object=monitor_v2_alarm_create_object, ) + + def update_with_http_info(self, monitor_v2_alarm_create_object: MonitorV2AlarmCreateObject) -> ApiResponse: + """ + Update the AlarmInstance with HTTP info + + :param monitor_v2_alarm_create_object: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info(monitor_v2_alarm_create_object=monitor_v2_alarm_create_object, ) + + async def update_with_http_info_async(self, monitor_v2_alarm_create_object: MonitorV2AlarmCreateObject) -> ApiResponse: + """ + Asynchronous coroutine to update the AlarmInstance with HTTP info + + :param monitor_v2_alarm_create_object: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async(monitor_v2_alarm_create_object=monitor_v2_alarm_create_object, ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) + return ''.format(context) + +class AlarmContext(InstanceContext): + + class MonitorV2AlarmCreateObject(object): + """ + :ivar friendly_name: Friendly name for alarm + :ivar query_type: + :ivar query: Value to query for + :ivar trigger_value: Threshold to send customer alarm notification + :ivar time_window: + :ivar email: Email notifications to send + :ivar webhook: Webhook notification to send + :ivar console_indicator: Whether to send console notifications + :ivar description: Description for the alarm. + :ivar enabled: Is alarm enbled? Default is true. + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.query_type: Optional["AlarmInstance.QueryType"] = payload.get("query_type") + self.query: Optional[str] = payload.get("query") + self.trigger_value: Optional[int] = payload.get("trigger_value") + self.time_window: Optional["AlarmInstance.TimeWindow"] = payload.get("time_window") + self.email: Optional[List[str]] = payload.get("email") + self.webhook: Optional[str] = payload.get("webhook") + self.console_indicator: Optional[bool] = payload.get("console_indicator") + self.description: Optional[str] = payload.get("description") + self.enabled: Optional[bool] = payload.get("enabled") + + def to_dict(self): + return { + + "friendly_name": self.friendly_name, + "query_type": self.query_type, + "query": self.query, + "trigger_value": self.trigger_value, + "time_window": self.time_window, + "email": self.email, + "webhook": self.webhook, + "console_indicator": self.console_indicator, + "description": self.description, + "enabled": self.enabled, + } + + + def __init__(self, version: Version, sid: str): + """ + Initialize the AlarmContext + + :param version: Version that contains the resource + :param sid: Sid + """ + super().__init__(version) + + + # Path Solution + self._solution = { + 'sid': sid, + } + self._uri = '/Alarms/{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 AlarmInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AlarmInstance 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 AlarmInstance + + + :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 AlarmInstance 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) -> AlarmInstance: + """ + Fetch the AlarmInstance + + + :returns: The fetched AlarmInstance + """ + payload, _, _ = self._fetch() + return AlarmInstance( + self._version, + payload, + sid=self._solution['sid'], + + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AlarmInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AlarmInstance( + 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) -> AlarmInstance: + """ + Asynchronous coroutine to fetch the AlarmInstance + + + :returns: The fetched AlarmInstance + """ + payload, _, _ = await self._fetch_async() + return AlarmInstance( + self._version, + payload, + sid=self._solution['sid'], + + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AlarmInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AlarmInstance( + self._version, + payload, + sid=self._solution['sid'], + + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + + def _update(self, monitor_v2_alarm_create_object: MonitorV2AlarmCreateObject) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = monitor_v2_alarm_create_object.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, monitor_v2_alarm_create_object: MonitorV2AlarmCreateObject) -> AlarmInstance: + """ + Update the AlarmInstance + + :param monitor_v2_alarm_create_object: + + :returns: The updated AlarmInstance + """ + payload, _, _ = self._update(monitor_v2_alarm_create_object=monitor_v2_alarm_create_object) + return AlarmInstance( + self._version, + payload, + sid=self._solution['sid'] + ) + + def update_with_http_info(self, monitor_v2_alarm_create_object: MonitorV2AlarmCreateObject) -> ApiResponse: + """ + Update the AlarmInstance and return response metadata + + :param monitor_v2_alarm_create_object: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(monitor_v2_alarm_create_object=monitor_v2_alarm_create_object) + instance = AlarmInstance( + self._version, + payload, + sid=self._solution['sid'] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, monitor_v2_alarm_create_object: MonitorV2AlarmCreateObject) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = monitor_v2_alarm_create_object.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, monitor_v2_alarm_create_object: MonitorV2AlarmCreateObject) -> AlarmInstance: + """ + Asynchronous coroutine to update the AlarmInstance + + :param monitor_v2_alarm_create_object: + + :returns: The updated AlarmInstance + """ + payload, _, _ = await self._update_async(monitor_v2_alarm_create_object=monitor_v2_alarm_create_object) + return AlarmInstance( + self._version, + payload, + sid=self._solution['sid'] + ) + + async def update_with_http_info_async(self, monitor_v2_alarm_create_object: MonitorV2AlarmCreateObject) -> ApiResponse: + """ + Asynchronous coroutine to update the AlarmInstance and return response metadata + + :param monitor_v2_alarm_create_object: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(monitor_v2_alarm_create_object=monitor_v2_alarm_create_object) + instance = AlarmInstance( + 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 AlarmPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AlarmInstance: + """ + Build an instance of AlarmInstance + + :param payload: Payload response from the API + """ + return AlarmInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + + + + +class AlarmList(ListResource): + + class MonitorV2AlarmCreateObject(object): + """ + :ivar friendly_name: Friendly name for alarm + :ivar query_type: + :ivar query: Value to query for + :ivar trigger_value: Threshold to send customer alarm notification + :ivar time_window: + :ivar email: Email notifications to send + :ivar webhook: Webhook notification to send + :ivar console_indicator: Whether to send console notifications + :ivar description: Description for the alarm. + :ivar enabled: Is alarm enbled? Default is true. + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.query_type: Optional["AlarmInstance.QueryType"] = payload.get("query_type") + self.query: Optional[str] = payload.get("query") + self.trigger_value: Optional[int] = payload.get("trigger_value") + self.time_window: Optional["AlarmInstance.TimeWindow"] = payload.get("time_window") + self.email: Optional[List[str]] = payload.get("email") + self.webhook: Optional[str] = payload.get("webhook") + self.console_indicator: Optional[bool] = payload.get("console_indicator") + self.description: Optional[str] = payload.get("description") + self.enabled: Optional[bool] = payload.get("enabled") + + def to_dict(self): + return { + + "friendly_name": self.friendly_name, + "query_type": self.query_type, + "query": self.query, + "trigger_value": self.trigger_value, + "time_window": self.time_window, + "email": self.email, + "webhook": self.webhook, + "console_indicator": self.console_indicator, + "description": self.description, + "enabled": self.enabled, + } + + + def __init__(self, version: Version): + """ + Initialize the AlarmList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + + self._uri = '/Alarms' + + + + + + + def _create(self, monitor_v2_alarm_create_object: MonitorV2AlarmCreateObject) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = monitor_v2_alarm_create_object.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, monitor_v2_alarm_create_object: MonitorV2AlarmCreateObject) -> AlarmInstance: + """ + Create the AlarmInstance + + :param monitor_v2_alarm_create_object: + + :returns: The created AlarmInstance + """ + payload, _, _ = self._create(monitor_v2_alarm_create_object=monitor_v2_alarm_create_object) + return AlarmInstance(self._version, payload) + + def create_with_http_info(self, monitor_v2_alarm_create_object: MonitorV2AlarmCreateObject) -> ApiResponse: + """ + Create the AlarmInstance and return response metadata + + :param monitor_v2_alarm_create_object: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(monitor_v2_alarm_create_object=monitor_v2_alarm_create_object) + instance = AlarmInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, monitor_v2_alarm_create_object: MonitorV2AlarmCreateObject) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = monitor_v2_alarm_create_object.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, monitor_v2_alarm_create_object: MonitorV2AlarmCreateObject) -> AlarmInstance: + """ + Asynchronously create the AlarmInstance + + :param monitor_v2_alarm_create_object: + + :returns: The created AlarmInstance + """ + payload, _, _ = await self._create_async(monitor_v2_alarm_create_object=monitor_v2_alarm_create_object) + return AlarmInstance(self._version, payload) + + async def create_with_http_info_async(self, monitor_v2_alarm_create_object: MonitorV2AlarmCreateObject) -> ApiResponse: + """ + Asynchronously create the AlarmInstance and return response metadata + + :param monitor_v2_alarm_create_object: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(monitor_v2_alarm_create_object=monitor_v2_alarm_create_object) + instance = AlarmInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + + def stream(self, + + sort_order: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AlarmInstance]: + """ + Streams AlarmInstance records from the API as a generator stream. + This operation lazily loads records 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_order: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + sort_order=sort_order, + page_size=limits['page_size'] + ) + + return self._version.stream(page, limits['limit']) + + async def stream_async(self, + + sort_order: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AlarmInstance]: + """ + Asynchronously streams AlarmInstance records from the API as a generator stream. + This operation lazily loads records 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_order: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + sort_order=sort_order, + page_size=limits['page_size'] + ) + + return self._version.stream_async(page, limits['limit']) + + def stream_with_http_info(self, + + sort_order: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AlarmInstance and returns headers from first page + + + :param str sort_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 + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + sort_order=sort_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, + + sort_order: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AlarmInstance and returns headers from first page + + + :param str sort_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 + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + sort_order=sort_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, + + sort_order: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AlarmInstance]: + """ + Lists AlarmInstance 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_order: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list(self.stream( + sort_order=sort_order, + limit=limit, + page_size=page_size, + )) + + async def list_async(self, + + sort_order: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AlarmInstance]: + """ + Asynchronously lists AlarmInstance 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_order: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [record async for record in await self.stream_async( + sort_order=sort_order, + limit=limit, + page_size=page_size, + )] + + def list_with_http_info(self, + + sort_order: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AlarmInstance and returns headers from first page + + + :param str sort_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 + """ + generator, status_code, headers = self.stream_with_http_info( + sort_order=sort_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, + + sort_order: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AlarmInstance and returns headers from first page + + + :param str sort_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 + """ + generator, status_code, headers = await self.stream_with_http_info_async( + sort_order=sort_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, + + sort_order: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AlarmPage: + """ + Retrieve a single page of AlarmInstance records from the API. + Request is executed immediately + + :param sort_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 AlarmInstance + """ + data = values.of({ + 'SortOrder': sort_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 AlarmPage(self._version, response) + + async def page_async(self, + + sort_order: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AlarmPage: + """ + Asynchronously retrieve a single page of AlarmInstance records from the API. + Request is executed immediately + + :param sort_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 AlarmInstance + """ + data = values.of({ + 'SortOrder': sort_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 AlarmPage(self._version, response) + + def page_with_http_info(self, + + sort_order: Union[str, object] = 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_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 AlarmPage, status code, and headers + """ + data = values.of({ + 'SortOrder': sort_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 = AlarmPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async(self, + + sort_order: Union[str, object] = 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_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 AlarmPage, status code, and headers + """ + data = values.of({ + 'SortOrder': sort_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 = AlarmPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> AlarmPage: + """ + Retrieve a specific page of AlarmInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AlarmInstance + """ + response = self._version.domain.twilio.request( + 'GET', + target_url + ) + return AlarmPage(self._version, response) + + async def get_page_async(self, target_url: str) -> AlarmPage: + """ + Asynchronously retrieve a specific page of AlarmInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AlarmInstance + """ + response = await self._version.domain.twilio.request_async( + 'GET', + target_url + ) + return AlarmPage(self._version, response) + + + + def get(self, sid: str) -> AlarmContext: + """ + Constructs a AlarmContext + + :param sid: Sid + """ + return AlarmContext(self._version, sid=sid) + + def __call__(self, sid: str) -> AlarmContext: + """ + Constructs a AlarmContext + + :param sid: Sid + """ + return AlarmContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return '' + diff --git a/twilio/rest/monitor/v2/status.py b/twilio/rest/monitor/v2/status.py new file mode 100644 index 000000000..a3ea9360e --- /dev/null +++ b/twilio/rest/monitor/v2/status.py @@ -0,0 +1,222 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Alarms + Manages Twilio Alarms + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + + +from datetime import date, datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator, Protocol +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 StatusInstance(InstanceResource): + + class MonitorV2AlarmStatus(object): + """ + :ivar enabled: status of alarm + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.enabled: Optional[bool] = payload.get("enabled") + + def to_dict(self): + return { + + "enabled": self.enabled, + } + + + + """ + :ivar message: Error message + :ivar code: Twilio error code + :ivar user_error: Indicates if it was a user error + :ivar http_status_code: Http error code returned + :ivar params: + :ivar more_info: More information link + :ivar status: HTTP status code + """ + + def __init__(self, version: Version, payload:Dict[str, Any], sid: Optional[str] = None): + super().__init__(version) + + + self.message: Optional[str] = payload.get("message") + self.code: Optional[int] = deserialize.integer(payload.get("code")) + self.user_error: Optional[bool] = payload.get("user_error") + self.http_status_code: Optional[int] = deserialize.integer(payload.get("http_status_code")) + self.params: Optional[Dict[str, str]] = payload.get("params") + self.more_info: Optional[str] = payload.get("more_info") + self.status: Optional[int] = deserialize.integer(payload.get("status")) + + + self._solution = { + "sid": sid or self.sid, + } + + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) + return ''.format(context) + + + + +class StatusList(ListResource): + + class MonitorV2AlarmStatus(object): + """ + :ivar enabled: status of alarm + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.enabled: Optional[bool] = payload.get("enabled") + + def to_dict(self): + return { + + "enabled": self.enabled, + } + + + def __init__(self, version: Version, sid: str): + """ + Initialize the StatusList + + :param version: Version that contains the resource + :param sid: Sid + + """ + super().__init__(version) + + + # Path Solution + self._solution = { 'sid': sid, } + self._uri = '/Alarms/{sid}/status'.format(**self._solution) + + + + + def _update(self, monitor_v2_alarm_status: MonitorV2AlarmStatus) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = monitor_v2_alarm_status.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='PUT', uri=self._uri, data=data, headers=headers) + + def update(self, monitor_v2_alarm_status: MonitorV2AlarmStatus) -> StatusInstance: + """ + Update the StatusInstance + + :param monitor_v2_alarm_status: + + :returns: The updated StatusInstance + """ + payload, _, _ = self._update(monitor_v2_alarm_status=monitor_v2_alarm_status) + return StatusInstance(self._version, payload, sid=self._solution['sid']) + + def update_with_http_info(self, monitor_v2_alarm_status: MonitorV2AlarmStatus) -> ApiResponse: + """ + Update the StatusInstance and return response metadata + + :param monitor_v2_alarm_status: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(monitor_v2_alarm_status=monitor_v2_alarm_status) + instance = StatusInstance(self._version, payload, sid=self._solution['sid']) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, monitor_v2_alarm_status: MonitorV2AlarmStatus) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = monitor_v2_alarm_status.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='PUT', uri=self._uri, data=data, headers=headers) + + async def update_async(self, monitor_v2_alarm_status: MonitorV2AlarmStatus) -> StatusInstance: + """ + Asynchronously update the StatusInstance + + :param monitor_v2_alarm_status: + + :returns: The updated StatusInstance + """ + payload, _, _ = await self._update_async(monitor_v2_alarm_status=monitor_v2_alarm_status) + return StatusInstance(self._version, payload, sid=self._solution['sid']) + + async def update_with_http_info_async(self, monitor_v2_alarm_status: MonitorV2AlarmStatus) -> ApiResponse: + """ + Asynchronously update the StatusInstance and return response metadata + + :param monitor_v2_alarm_status: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(monitor_v2_alarm_status=monitor_v2_alarm_status) + instance = StatusInstance(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/preview_iam/organizations/__init__.py b/twilio/rest/preview_iam/organizations/__init__.py new file mode 100644 index 000000000..9e7651138 --- /dev/null +++ b/twilio/rest/preview_iam/organizations/__init__.py @@ -0,0 +1,59 @@ +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.organizations.account import AccountList +from twilio.rest.preview_iam.organizations.role_assignment import RoleAssignmentList +from twilio.rest.preview_iam.organizations.user import UserList + + +class Organizations(Version): + + def __init__(self, domain: Domain): + """ + Initialize the Organizations version of PreviewIam + + :param domain: The Twilio.preview_iam domain + """ + super().__init__(domain, "Organizations") + self._accounts: Optional[AccountList] = None + self._role_assignments: Optional[RoleAssignmentList] = None + self._users: Optional[UserList] = None + + @property + def accounts(self) -> AccountList: + if self._accounts is None: + self._accounts = AccountList(self) + return self._accounts + + @property + def role_assignments(self) -> RoleAssignmentList: + if self._role_assignments is None: + self._role_assignments = RoleAssignmentList(self) + return self._role_assignments + + @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/preview_iam/organizations/account.py b/twilio/rest/preview_iam/organizations/account.py new file mode 100644 index 000000000..fe5d78174 --- /dev/null +++ b/twilio/rest/preview_iam/organizations/account.py @@ -0,0 +1,687 @@ +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 date, datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator, Protocol +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 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: Optional[str] = None, account_sid: Optional[str] = None): + super().__init__(version) + + + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional[str] = payload.get("status") + self.owner_sid: Optional[str] = payload.get("owner_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime(payload.get("date_created")) + + + self._solution = { + "organization_sid": organization_sid or self.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, self._solution) + + async def page_async(self, + + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AccountPage: + """ + Asynchronously retrieve a single page of AccountInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AccountInstance + """ + data = values.of({ + 'PageToken': page_token, + 'Page': page_number, + 'PageSize': page_size, + }) + + headers = values.of({ + 'Content-Type': 'application/x-www-form-urlencoded' + }) + + + headers["Accept"] = "application/json" + + + response = await self._version.page_async(method='GET', uri=self._uri, params=data, headers=headers) + return AccountPage(self._version, response, self._solution) + + def 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, 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, 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, self._solution) + + async def get_page_async(self, target_url: str) -> AccountPage: + """ + Asynchronously retrieve a specific page of AccountInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AccountInstance + """ + response = await self._version.domain.twilio.request_async( + 'GET', + target_url + ) + return AccountPage(self._version, response, self._solution) + + + + def get(self, organization_sid: str, account_sid: str) -> AccountContext: + """ + Constructs a AccountContext + + :param organization_sid: + :param account_sid: + """ + return AccountContext(self._version, organization_sid=organization_sid, account_sid=account_sid) + + def __call__(self, organization_sid: str, account_sid: str) -> AccountContext: + """ + Constructs a AccountContext + + :param organization_sid: + :param account_sid: + """ + return AccountContext(self._version, organization_sid=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/organizations/role_assignment.py b/twilio/rest/preview_iam/organizations/role_assignment.py new file mode 100644 index 000000000..42e94e05d --- /dev/null +++ b/twilio/rest/preview_iam/organizations/role_assignment.py @@ -0,0 +1,897 @@ +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 date, datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator, Protocol +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 RoleAssignmentInstance(InstanceResource): + + class PublicApiCreateRoleAssignmentRequest(object): + """ + :ivar role_sid: Twilio Role Sid representing assigned role + :ivar scope: Twilio Sid representing scope of this assignment + :ivar identity: Twilio Sid representing identity of this assignment + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.role_sid: Optional[str] = payload.get("role_sid") + self.scope: Optional[str] = payload.get("scope") + self.identity: Optional[str] = payload.get("identity") + + def to_dict(self): + return { + + "role_sid": self.role_sid, + "scope": self.scope, + "identity": self.identity, + } + + + + """ + :ivar sid: Twilio Role Assignment Sid representing this role assignment + :ivar role_sid: Twilio Role Sid representing assigned role + :ivar scope: Twilio Sid representing identity of this assignment + :ivar identity: Twilio Sid representing scope of this assignment + :ivar code: Twilio-specific error code + :ivar message: Error message + :ivar more_info: Link to Error Code References + :ivar status: HTTP response status code + """ + + def __init__(self, version: Version, payload:Dict[str, Any], organization_sid: Optional[str] = None, role_assignment_sid: Optional[str] = None): + super().__init__(version) + + + self.sid: Optional[str] = payload.get("sid") + self.role_sid: Optional[str] = payload.get("role_sid") + self.scope: Optional[str] = payload.get("scope") + self.identity: Optional[str] = payload.get("identity") + self.code: Optional[int] = payload.get("code") + self.message: Optional[str] = payload.get("message") + self.more_info: Optional[str] = payload.get("moreInfo") + self.status: Optional[int] = payload.get("status") + + + self._solution = { + "organization_sid": organization_sid or self.organization_sid, + "role_assignment_sid": role_assignment_sid or self.role_assignment_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'], role_assignment_sid=self._solution['role_assignment_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 + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.role_sid: Optional[str] = payload.get("role_sid") + self.scope: Optional[str] = payload.get("scope") + self.identity: Optional[str] = payload.get("identity") + + def to_dict(self): + return { + + "role_sid": self.role_sid, + "scope": self.scope, + "identity": self.identity, + } + + + def __init__(self, version: Version, organization_sid: str, role_assignment_sid: str): + """ + Initialize the RoleAssignmentContext + + :param version: Version that contains the resource + :param organization_sid: + :param role_assignment_sid: + """ + super().__init__(version) + + + # Path Solution + self._solution = { + 'organization_sid': organization_sid, + 'role_assignment_sid': role_assignment_sid, + } + self._uri = '/{organization_sid}/RoleAssignments/{role_assignment_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 + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.role_sid: Optional[str] = payload.get("role_sid") + self.scope: Optional[str] = payload.get("scope") + self.identity: Optional[str] = payload.get("identity") + + def to_dict(self): + return { + + "role_sid": self.role_sid, + "scope": self.scope, + "identity": self.identity, + } + + + def __init__(self, version: Version, organization_sid: str): + """ + Initialize the RoleAssignmentList + + :param version: Version that contains the resource + :param organization_sid: + + """ + super().__init__(version) + + + # Path Solution + self._solution = { 'organization_sid': organization_sid, } + self._uri = '/{organization_sid}/RoleAssignments'.format(**self._solution) + + + + + def _create(self, public_api_create_role_assignment_request: PublicApiCreateRoleAssignmentRequest) -> 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, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RoleAssignmentInstance]: + """ + Streams RoleAssignmentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str identity: + :param str scope: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + identity=identity, + scope=scope, + page_size=limits['page_size'] + ) + + return self._version.stream(page, limits['limit']) + + async def stream_async(self, + + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RoleAssignmentInstance]: + """ + Asynchronously streams RoleAssignmentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str identity: + :param str scope: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + identity=identity, + scope=scope, + page_size=limits['page_size'] + ) + + return self._version.stream_async(page, limits['limit']) + + def stream_with_http_info(self, + + identity: Union[str, object] = values.unset, + scope: 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 limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. 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, + page_size=limits['page_size'] + ) + + generator = self._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, + 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 limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. 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, + page_size=limits['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, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoleAssignmentInstance]: + """ + Lists RoleAssignmentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str identity: + :param str scope: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list(self.stream( + identity=identity, + scope=scope, + limit=limit, + page_size=page_size, + )) + + async def list_async(self, + + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoleAssignmentInstance]: + """ + Asynchronously lists RoleAssignmentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str identity: + :param str scope: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [record async for record in await self.stream_async( + identity=identity, + scope=scope, + limit=limit, + page_size=page_size, + )] + + def list_with_http_info(self, + + identity: Union[str, object] = values.unset, + scope: 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 limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with 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, + limit=limit, + page_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, + 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 limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with 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, + limit=limit, + 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, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RoleAssignmentPage: + """ + Retrieve a single page of RoleAssignmentInstance records from the API. + Request is executed immediately + + :param identity: + :param scope: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoleAssignmentInstance + """ + data = values.of({ + 'Identity': identity, + 'Scope': scope, + 'PageToken': page_token, + 'Page': page_number, + 'PageSize': page_size, + }) + + headers = values.of({ + 'Content-Type': 'application/x-www-form-urlencoded' + }) + + + headers["Accept"] = "application/json" + + + response = self._version.page(method='GET', uri=self._uri, params=data, headers=headers) + return RoleAssignmentPage(self._version, response, self._solution) + + async def page_async(self, + + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RoleAssignmentPage: + """ + Asynchronously retrieve a single page of RoleAssignmentInstance records from the API. + Request is executed immediately + + :param identity: + :param scope: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoleAssignmentInstance + """ + data = values.of({ + 'Identity': identity, + 'Scope': scope, + 'PageToken': page_token, + 'Page': page_number, + 'PageSize': page_size, + }) + + headers = values.of({ + 'Content-Type': 'application/x-www-form-urlencoded' + }) + + + headers["Accept"] = "application/json" + + + response = await self._version.page_async(method='GET', uri=self._uri, params=data, headers=headers) + return RoleAssignmentPage(self._version, response, self._solution) + + def page_with_http_info(self, + + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param identity: + :param scope: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RoleAssignmentPage, status code, and headers + """ + data = values.of({ + 'Identity': identity, + 'Scope': scope, + 'PageToken': page_token, + 'Page': page_number, + 'PageSize': page_size, + }) + + headers = values.of({ + 'Content-Type': 'application/x-www-form-urlencoded' + }) + + + headers["Accept"] = "application/json" + + + response, status_code, response_headers = self._version.page_with_response_info(method='GET', uri=self._uri, params=data, headers=headers) + page = RoleAssignmentPage(self._version, response, 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, + page_token: Union[str, object] = values.unset, + 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 page_token: PageToken provided by the API + :param page_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, + 'PageToken': page_token, + 'Page': page_number, + 'PageSize': page_size, + }) + + headers = values.of({ + 'Content-Type': 'application/x-www-form-urlencoded' + }) + + + headers["Accept"] = "application/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, 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, self._solution) + + async def get_page_async(self, target_url: str) -> RoleAssignmentPage: + """ + Asynchronously retrieve a specific page of RoleAssignmentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoleAssignmentInstance + """ + response = await self._version.domain.twilio.request_async( + 'GET', + target_url + ) + return RoleAssignmentPage(self._version, response, self._solution) + + + + def get(self, organization_sid: str, role_assignment_sid: str) -> RoleAssignmentContext: + """ + Constructs a RoleAssignmentContext + + :param organization_sid: + :param role_assignment_sid: + """ + return RoleAssignmentContext(self._version, organization_sid=organization_sid, role_assignment_sid=role_assignment_sid) + + def __call__(self, organization_sid: str, role_assignment_sid: str) -> RoleAssignmentContext: + """ + Constructs a RoleAssignmentContext + + :param organization_sid: + :param role_assignment_sid: + """ + return RoleAssignmentContext(self._version, organization_sid=organization_sid, role_assignment_sid=role_assignment_sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return '' + diff --git a/twilio/rest/preview_iam/organizations/user.py b/twilio/rest/preview_iam/organizations/user.py new file mode 100644 index 000000000..bb397c540 --- /dev/null +++ b/twilio/rest/preview_iam/organizations/user.py @@ -0,0 +1,1495 @@ +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 date, datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator, Protocol +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 UserInstance(InstanceResource): + + class ScimEmailAddress(object): + """ + :ivar primary: Indicates if this email address is the primary one + :ivar value: The actual email address value + :ivar type: The type of email address (e.g., work, home, etc.) + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.primary: Optional[bool] = payload.get("primary") + self.value: Optional[str] = payload.get("value") + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + + "primary": self.primary, + "value": self.value, + "type": self.type, + } + + class ScimMeta(object): + """ + :ivar resource_type: Indicates the type of the resource + :ivar created: The date and time when the resource was created in the system + :ivar last_modified: The date and time when the resource was last modified + :ivar version: A version identifier for the resource. This can be used to manage resource versioning and concurrency control. + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.resource_type: Optional[str] = payload.get("resource_type") + self.created: Optional[datetime] = payload.get("created") + self.last_modified: Optional[datetime] = payload.get("last_modified") + self.version: Optional[str] = payload.get("version") + + def to_dict(self): + return { + + "resource_type": self.resource_type, + "created": self.created, + "last_modified": self.last_modified, + "version": self.version, + } + + class ScimName(object): + """ + :ivar given_name: The user's first or given name + :ivar family_name: The user's last or family name + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.given_name: Optional[str] = payload.get("given_name") + self.family_name: Optional[str] = payload.get("family_name") + + def to_dict(self): + return { + + "given_name": self.given_name, + "family_name": self.family_name, + } + + class ScimUser(object): + """ + :ivar id: Unique Twilio user sid + :ivar external_id: External unique resource id defined by provisioning client + :ivar user_name: Unique username, MUST be same as primary email address + :ivar display_name: User friendly display name + :ivar name: + :ivar emails: Email address list of the user. Primary email must be defined if there are more than 1 email. Primary email must match the username. + :ivar active: Indicates whether the user is active + :ivar locale: User's locale + :ivar timezone: User's time zone + :ivar schemas: An array of URIs that indicate the schemas supported for this user resource + :ivar meta: + :ivar detail: A human-readable description of the error + :ivar scim_type: A scimType error code as defined in RFC7644 + :ivar status: Http status code + :ivar code: Twilio-specific error code + :ivar more_info: Link to Error Code References + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.id: Optional[str] = payload.get("id") + self.external_id: Optional[str] = payload.get("external_id") + self.user_name: Optional[str] = payload.get("user_name") + self.display_name: Optional[str] = payload.get("display_name") + self.name: Optional[UserList.ScimName] = payload.get("name") + self.emails: Optional[List[UserList.ScimEmailAddress]] = payload.get("emails") + self.active: Optional[bool] = payload.get("active") + self.locale: Optional[str] = payload.get("locale") + self.timezone: Optional[str] = payload.get("timezone") + self.schemas: Optional[List[str]] = payload.get("schemas") + self.meta: Optional[UserList.ScimMeta] = payload.get("meta") + self.detail: Optional[str] = payload.get("detail") + self.scim_type: Optional[str] = payload.get("scim_type") + self.status: Optional[str] = payload.get("status") + self.code: Optional[int] = payload.get("code") + self.more_info: Optional[str] = payload.get("more_info") + + def to_dict(self): + return { + + "id": self.id, + "externalId": self.external_id, + "userName": self.user_name, + "displayName": self.display_name, + "name": self.name.to_dict() if self.name is not None else None , + "emails": [emails.to_dict() for emails in self.emails] if self.emails is not None else None, + "active": self.active, + "locale": self.locale, + "timezone": self.timezone, + "schemas": self.schemas, + "meta": self.meta.to_dict() if self.meta is not None else None , + "detail": self.detail, + "scimType": self.scim_type, + "status": self.status, + "code": self.code, + "moreInfo": self.more_info, + } + + + + """ + :ivar id: Unique Twilio user sid + :ivar external_id: External unique resource id defined by provisioning client + :ivar user_name: Unique username, MUST be same as primary email address + :ivar display_name: User friendly display name + :ivar name: + :ivar emails: Email address list of the user. Primary email must be defined if there are more than 1 email. Primary email must match the username. + :ivar active: Indicates whether the user is active + :ivar locale: User's locale + :ivar timezone: User's time zone + :ivar schemas: An array of URIs that indicate the schemas supported for this user resource + :ivar meta: + :ivar detail: A human-readable description of the error + :ivar scim_type: A scimType error code as defined in RFC7644 + :ivar status: Http status code + :ivar code: Twilio-specific error code + :ivar more_info: Link to Error Code References + """ + + def __init__(self, version: Version, payload:Dict[str, Any], organization_sid: Optional[str] = None, user_sid: Optional[str] = None): + super().__init__(version) + + + self.id: Optional[str] = payload.get("id") + self.external_id: Optional[str] = payload.get("externalId") + self.user_name: Optional[str] = payload.get("userName") + self.display_name: Optional[str] = payload.get("displayName") + self.name: Optional[UserList.str] = payload.get("name") + self.emails: Optional[List[UserList.str]] = payload.get("emails") + self.active: Optional[bool] = payload.get("active") + self.locale: Optional[str] = payload.get("locale") + self.timezone: Optional[str] = payload.get("timezone") + self.schemas: Optional[List[str]] = payload.get("schemas") + self.meta: Optional[UserList.str] = payload.get("meta") + self.detail: Optional[str] = payload.get("detail") + self.scim_type: Optional[str] = payload.get("scimType") + self.status: Optional[str] = payload.get("status") + self.code: Optional[int] = payload.get("code") + self.more_info: Optional[str] = payload.get("moreInfo") + + + self._solution = { + "organization_sid": organization_sid or self.organization_sid, + "user_sid": user_sid or self.user_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, organization_sid=self._solution['organization_sid'], user_sid=self._solution['user_sid'],) + return self._context + + + def delete(self) -> bool: + """ + Deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def 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 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("resource_type") + self.created: Optional[datetime] = payload.get("created") + self.last_modified: Optional[datetime] = payload.get("last_modified") + self.version: Optional[str] = payload.get("version") + + def to_dict(self): + return { + + "resource_type": self.resource_type, + "created": self.created, + "last_modified": self.last_modified, + "version": self.version, + } + + class ScimName(object): + """ + :ivar given_name: The user's first or given name + :ivar family_name: The user's last or family name + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.given_name: Optional[str] = payload.get("given_name") + self.family_name: Optional[str] = payload.get("family_name") + + def to_dict(self): + return { + + "given_name": self.given_name, + "family_name": self.family_name, + } + + class ScimUser(object): + """ + :ivar id: Unique Twilio user sid + :ivar external_id: External unique resource id defined by provisioning client + :ivar user_name: Unique username, MUST be same as primary email address + :ivar display_name: User friendly display name + :ivar name: + :ivar emails: Email address list of the user. Primary email must be defined if there are more than 1 email. Primary email must match the username. + :ivar active: Indicates whether the user is active + :ivar locale: User's locale + :ivar timezone: User's time zone + :ivar schemas: An array of URIs that indicate the schemas supported for this user resource + :ivar meta: + :ivar detail: A human-readable description of the error + :ivar scim_type: A scimType error code as defined in RFC7644 + :ivar status: Http status code + :ivar code: Twilio-specific error code + :ivar more_info: Link to Error Code References + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.id: Optional[str] = payload.get("id") + self.external_id: Optional[str] = payload.get("external_id") + self.user_name: Optional[str] = payload.get("user_name") + self.display_name: Optional[str] = payload.get("display_name") + self.name: Optional[UserList.ScimName] = payload.get("name") + self.emails: Optional[List[UserList.ScimEmailAddress]] = payload.get("emails") + self.active: Optional[bool] = payload.get("active") + self.locale: Optional[str] = payload.get("locale") + self.timezone: Optional[str] = payload.get("timezone") + self.schemas: Optional[List[str]] = payload.get("schemas") + self.meta: Optional[UserList.ScimMeta] = payload.get("meta") + self.detail: Optional[str] = payload.get("detail") + self.scim_type: Optional[str] = payload.get("scim_type") + self.status: Optional[str] = payload.get("status") + self.code: Optional[int] = payload.get("code") + self.more_info: Optional[str] = payload.get("more_info") + + def to_dict(self): + return { + + "id": self.id, + "externalId": self.external_id, + "userName": self.user_name, + "displayName": self.display_name, + "name": self.name.to_dict() if self.name is not None else None , + "emails": [emails.to_dict() for emails in self.emails] if self.emails is not None else None, + "active": self.active, + "locale": self.locale, + "timezone": self.timezone, + "schemas": self.schemas, + "meta": self.meta.to_dict() if self.meta is not None else None , + "detail": self.detail, + "scimType": self.scim_type, + "status": self.status, + "code": self.code, + "moreInfo": self.more_info, + } + + + def __init__(self, version: Version, organization_sid: str, user_sid: str): + """ + Initialize the UserContext + + :param version: Version that contains the resource + :param organization_sid: + :param user_sid: + """ + super().__init__(version) + + + # Path Solution + self._solution = { + 'organization_sid': organization_sid, + 'user_sid': user_sid, + } + self._uri = '/{organization_sid}/scim/Users/{user_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 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'], + user_sid=self._solution['user_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, + organization_sid=self._solution['organization_sid'], + user_sid=self._solution['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/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'], + user_sid=self._solution['user_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, + organization_sid=self._solution['organization_sid'], + user_sid=self._solution['user_sid'], + + ) + 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'], + user_sid=self._solution['user_sid'] + ) + + 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'], + user_sid=self._solution['user_sid'] + ) + 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'], + user_sid=self._solution['user_sid'] + ) + + 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'], + user_sid=self._solution['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 UserPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserInstance: + """ + Build an instance of UserInstance + + :param payload: Payload response from the API + """ + return UserInstance(self._version, payload, organization_sid=self._solution["organization_sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + + + + +class UserList(ListResource): + + class ScimEmailAddress(object): + """ + :ivar primary: Indicates if this email address is the primary one + :ivar value: The actual email address value + :ivar type: The type of email address (e.g., work, home, etc.) + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.primary: Optional[bool] = payload.get("primary") + self.value: Optional[str] = payload.get("value") + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + + "primary": self.primary, + "value": self.value, + "type": self.type, + } + + class ScimMeta(object): + """ + :ivar resource_type: Indicates the type of the resource + :ivar created: The date and time when the resource was created in the system + :ivar last_modified: The date and time when the resource was last modified + :ivar version: A version identifier for the resource. This can be used to manage resource versioning and concurrency control. + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.resource_type: Optional[str] = payload.get("resource_type") + self.created: Optional[datetime] = payload.get("created") + self.last_modified: Optional[datetime] = payload.get("last_modified") + self.version: Optional[str] = payload.get("version") + + def to_dict(self): + return { + + "resource_type": self.resource_type, + "created": self.created, + "last_modified": self.last_modified, + "version": self.version, + } + + class ScimName(object): + """ + :ivar given_name: The user's first or given name + :ivar family_name: The user's last or family name + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.given_name: Optional[str] = payload.get("given_name") + self.family_name: Optional[str] = payload.get("family_name") + + def to_dict(self): + return { + + "given_name": self.given_name, + "family_name": self.family_name, + } + + class ScimUser(object): + """ + :ivar id: Unique Twilio user sid + :ivar external_id: External unique resource id defined by provisioning client + :ivar user_name: Unique username, MUST be same as primary email address + :ivar display_name: User friendly display name + :ivar name: + :ivar emails: Email address list of the user. Primary email must be defined if there are more than 1 email. Primary email must match the username. + :ivar active: Indicates whether the user is active + :ivar locale: User's locale + :ivar timezone: User's time zone + :ivar schemas: An array of URIs that indicate the schemas supported for this user resource + :ivar meta: + :ivar detail: A human-readable description of the error + :ivar scim_type: A scimType error code as defined in RFC7644 + :ivar status: Http status code + :ivar code: Twilio-specific error code + :ivar more_info: Link to Error Code References + """ + + def __init__(self, payload: Dict[str, Any]): + + + self.id: Optional[str] = payload.get("id") + self.external_id: Optional[str] = payload.get("external_id") + self.user_name: Optional[str] = payload.get("user_name") + self.display_name: Optional[str] = payload.get("display_name") + self.name: Optional[UserList.ScimName] = payload.get("name") + self.emails: Optional[List[UserList.ScimEmailAddress]] = payload.get("emails") + self.active: Optional[bool] = payload.get("active") + self.locale: Optional[str] = payload.get("locale") + self.timezone: Optional[str] = payload.get("timezone") + self.schemas: Optional[List[str]] = payload.get("schemas") + self.meta: Optional[UserList.ScimMeta] = payload.get("meta") + self.detail: Optional[str] = payload.get("detail") + self.scim_type: Optional[str] = payload.get("scim_type") + self.status: Optional[str] = payload.get("status") + self.code: Optional[int] = payload.get("code") + self.more_info: Optional[str] = payload.get("more_info") + + def to_dict(self): + return { + + "id": self.id, + "externalId": self.external_id, + "userName": self.user_name, + "displayName": self.display_name, + "name": self.name.to_dict() if self.name is not None else None , + "emails": [emails.to_dict() for emails in self.emails] if self.emails is not None else None, + "active": self.active, + "locale": self.locale, + "timezone": self.timezone, + "schemas": self.schemas, + "meta": self.meta.to_dict() if self.meta is not None else None , + "detail": self.detail, + "scimType": self.scim_type, + "status": self.status, + "code": self.code, + "moreInfo": self.more_info, + } + + + def __init__(self, version: Version, organization_sid: str): + """ + Initialize the UserList + + :param version: Version that contains the resource + :param organization_sid: + + """ + super().__init__(version) + + + # Path Solution + self._solution = { 'organization_sid': organization_sid, } + self._uri = '/{organization_sid}/scim/Users'.format(**self._solution) + + + + + + + def _create(self, scim_user: ScimUser) -> 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, self._solution) + + async def page_async(self, + filter: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserPage: + """ + Asynchronously retrieve a single page of UserInstance records from the API. + Request is executed immediately + + :param filter: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserInstance + """ + data = values.of({ + 'filter': filter, + 'PageToken': page_token, + 'Page': page_number, + 'PageSize': page_size, + }) + + headers = values.of({ + 'Content-Type': 'application/x-www-form-urlencoded' + }) + + + headers["Accept"] = "application/scim+json" + + + response = await self._version.page_async(method='GET', uri=self._uri, params=data, headers=headers) + return UserPage(self._version, response, self._solution) + + def 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, 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, 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, self._solution) + + async def get_page_async(self, target_url: str) -> UserPage: + """ + Asynchronously retrieve a specific page of UserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance + """ + response = await self._version.domain.twilio.request_async( + 'GET', + target_url + ) + return UserPage(self._version, response, self._solution) + + + + def get(self, organization_sid: str, user_sid: str) -> UserContext: + """ + Constructs a UserContext + + :param organization_sid: + :param user_sid: + """ + return UserContext(self._version, organization_sid=organization_sid, user_sid=user_sid) + + def __call__(self, organization_sid: str, user_sid: str) -> UserContext: + """ + Constructs a UserContext + + :param organization_sid: + :param user_sid: + """ + return UserContext(self._version, organization_sid=organization_sid, user_sid=user_sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return '' +