### Complete PHLO Workflow Example Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/api-reference/phlo.md A comprehensive example demonstrating PHLO client initialization, retrieving a PHLO, and running it with input parameters. ```python import plivo # Initialize PHLO client auth_id = '' auth_token = '' phlo_id = '' phlo_client = plivo.phlo.RestClient(auth_id=auth_id, auth_token=auth_token) # Get the PHLO phlo = phlo_client.phlo.get(phlo_id) # Run the PHLO with input parameters response = phlo.run( to='14155551234', from_='14155555678', input_={ 'customer_name': 'Alice', 'order_number': 'ORD-789' } ) # Check response print(f"PHLO Request ID: {response.request_id}") print(f"PHLO ID: {response.phlo_id}") ``` -------------------------------- ### Example: Get, Update, and Delete Subaccount Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/api-reference/accounts.md Demonstrates the typical workflow for managing a subaccount: retrieving it by ID, updating its name, and then deleting it. ```python subaccount = client.subaccounts.get('SA1234567890123456') subaccount.update(name='New Name') subaccount.delete() ``` -------------------------------- ### Complete JWT Generation Example Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/api-reference/jwt.md A comprehensive example demonstrating the creation of a JWT with voice grants and its subsequent generation. ```APIDOC ## Complete JWT Generation Example ```python from plivo.utils import jwt import time auth_id = 'MA123456789012345678' auth_token = 'your_auth_token_here' endpoint_username = 'alice@example.com' # Create token valid for 5 minutes token = jwt.AccessToken( auth_id=auth_id, auth_token=auth_token, username=endpoint_username, valid_from=int(time.time()), lifetime=300 ) # Grant voice permissions (both incoming and outgoing) token.add_voice_grants(incoming=True, outgoing=True) # Generate JWT jwt_string = token.to_jwt() print(f"JWT Token: {jwt_string}") ``` ``` -------------------------------- ### Install Plivo Python SDK Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/README.md Install the Plivo Python SDK using pip. This command fetches and installs the latest stable version of the library. ```bash pip install plivo ``` -------------------------------- ### Complete JWT Generation Example Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/api-reference/jwt.md A comprehensive example demonstrating the creation of a JWT token with voice permissions and its subsequent generation. This includes setting authentication details, validity, and grants. ```python from plivo.utils import jwt import time auth_id = 'MA123456789012345678' auth_token = 'your_auth_token_here' endpoint_username = 'alice@example.com' # Create token valid for 5 minutes token = jwt.AccessToken( auth_id=auth_id, auth_token=auth_token, username=endpoint_username, valid_from=int(time.time()), lifetime=300 ) # Grant voice permissions (both incoming and outgoing) token.add_voice_grants(incoming=True, outgoing=True) # Generate JWT jwt_string = token.to_jwt() print(f"JWT Token: {jwt_string}") ``` -------------------------------- ### PHLO Client Initialization Example Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/configuration.md Instantiate the PHLO client with provided authentication credentials. ```python import plivo phlo_client = plivo.phlo.RestClient( auth_id='MA123456789012345678', auth_token='your_auth_token_here' ) ``` -------------------------------- ### Start Recording Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/api-reference/calls.md Initiates the recording of an active call with various configuration options. ```APIDOC ## Method: start_recording ### Description Start recording a call. ### Method Signature ```python Calls.start_recording(call_uuid, time_limit=None, file_format=None, transcription_type=None, transcription_url=None, transcription_method=None, transcription_report_type=None, callback_url=None, callback_method=None) ``` ### Parameters #### Path Parameters - **call_uuid** (str) - Yes - Call UUID #### Query Parameters - **time_limit** (int) - No - Max recording time in seconds - **file_format** (str) - No - Format: 'mp3' or 'wav' - **transcription_type** (str) - No - Transcription service - **transcription_url** (str) - No - Transcription callback URL - **transcription_method** (str) - No - HTTP method for transcription - **transcription_report_type** (str) - No - Report type - **callback_url** (str) - No - Recording completion callback - **callback_method** (str) - No - HTTP method for callback ### Request Example ```python response = client.calls.start_recording( 'call-uuid', file_format='mp3' ) ``` ### Response **Returns**: Response object ``` -------------------------------- ### Complete Plivo Numbers API Example Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/api-reference/numbers.md This comprehensive example demonstrates the workflow of searching for, buying, listing, updating, and releasing phone numbers using the Plivo Python SDK. ```python import plivo client = plivo.RestClient() # 1. Search for available numbers available = client.numbers.search( country_iso='US', region='CA', type='local', services='sms,voice' ) # 2. Buy first available if available: response = client.numbers.buy(available[0]) print(f"Purchased: {response.number}") # 3. List owned numbers owned = client.numbers.list(number_startswith='415') for num in owned: print(f"{num.number}: {num.alias}") # 4. Update number owned[0].update(alias='Main Support') # 5. Release number owned[0].delete() ``` -------------------------------- ### Create a WhatsApp Template Message Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/types.md Example of initializing a Template object for an order confirmation. Requires importing the Template class. ```python from plivo.utils.template import Template template = Template( name='order_confirmation', language='en_US', components=[ Component(type='header', ...), Component(type='body', ...) ] ) ``` -------------------------------- ### Start Stream Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/api-reference/calls.md Initiates audio streaming to or from a call, enabling real-time audio processing. ```APIDOC ## Method: start_stream ### Description Stream audio to/from call. ### Method Signature ```python Calls.start_stream(call_uuid, service_url, bidirectional=None, audio_track=None, stream_timeout=None, status_callback_url=None, status_callback_method=None, content_type=None, extra_headers=None) ``` ### Parameters #### Path Parameters - **call_uuid** (str) - Yes - Call UUID - **service_url** (str) - Yes - WebSocket service URL #### Query Parameters - **bidirectional** (bool) - No - Enable bidirectional stream - **audio_track** (str) - No - Audio track: 'inbound', 'outbound', 'both' - **stream_timeout** (int) - No - Stream timeout in seconds - **status_callback_url** (str) - No - Status callback URL - **status_callback_method** (str) - No - HTTP method for callback - **content_type** (str) - No - Content type - **extra_headers** (dict) - No - Extra HTTP headers ### Response **Returns**: Response object ``` -------------------------------- ### Create a WhatsApp Location Message Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/types.md Example of initializing a Location object with coordinates, name, and address. The properties are passed as keyword arguments. ```python from plivo.utils.location import Location location = Location(**{ "longitude": "122.148981", "latitude": "37.483307", "name": "Plivo HQ", "address": "1 Hacker Way" }) ``` -------------------------------- ### Create a WhatsApp Interactive Message Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/types.md Example of initializing an Interactive object for a button-based message. The structure is passed as keyword arguments. ```python from plivo.utils.interactive import Interactive interactive = Interactive(**{ "type": "button", "body": {"text": "Choose an option"}, "action": { "buttons": [ {"title": "Option 1", "id": "opt1"}, {"title": "Option 2", "id": "opt2"} ] } }) ``` -------------------------------- ### get Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/api-reference/applications.md Retrieve details of a specific application using its ID. ```APIDOC ## get ### Description Retrieve an application. ### Method GET (inferred from SDK usage) ### Endpoint /v1/Account/{Account_id}/Application/{app_id}/ ### Parameters #### Path Parameters - **Account_id** (str) - Required - Your Plivo API authentication ID - **app_id** (str) - Required - Application UUID #### Query Parameters - **callback_url** (str) - Optional - Async callback URL - **callback_method** (str) - Optional - HTTP method for callback ### Request Example ```python app = client.applications.get('app-uuid-here') print(f"App: {app.app_name}") print(f"Answer URL: {app.answer_url}") ``` ### Response #### Success Response (200) - **Application** (object) - Application object #### Response Example { "app_id": "some_app_id", "app_name": "My Voice App", "answer_url": "https://example.com/answer" } ``` -------------------------------- ### Create a Location Message Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/api-reference/utilities.md This example demonstrates how to create a Location object with coordinates, name, and address for a WhatsApp location message. ```python from plivo.utils.location import Location location = Location( longitude='122.148981', latitude='37.483307', name='Plivo HQ', address='1 Hacker Way, Menlo Park, CA' ) ``` -------------------------------- ### Get Application Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/api-reference/applications.md Refreshes and retrieves the current state of a specific application resource. ```APIDOC ## Get Application ### Description Refreshes and retrieves the current state of a specific application resource. ### Method Application.get ### Parameters This method does not take any parameters as it operates on an existing Application object. ### Response #### Success Response Returns the updated `Application` object. ### Example ```python app = client.applications.get('app-uuid') ``` ``` -------------------------------- ### Setup Environment Variables for Plivo SDK Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/configuration.md Set Plivo account ID and auth token as environment variables. These are used by the SDK if not explicitly passed to the RestClient constructor. ```bash export PLIVO_AUTH_ID='MA123456789012345678' export PLIVO_AUTH_TOKEN='your_token_here' ``` -------------------------------- ### Get Main Account Details Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/api-reference/accounts.md Retrieves the details of the main Plivo account. Requires an initialized Plivo client. ```python import plivo client = plivo.RestClient() account = client.account.get() print(f"Account: {account.auth_id}") print(f"Name: {account.name}") print(f"Cash Credits: {account.cash_credits}") ``` -------------------------------- ### Basic Resource Management Patterns Source: https://github.com/plivo/plivo-python/blob/master/README.md Demonstrates the standard interfaces for interacting with Plivo resources: create, get, update, delete, and list. The list method retrieves a maximum of 20 resources by default. ```python client.resources.create(*args, **kwargs) # Create client.resources.get(id=resource_identifier) # Get client.resources.update(id=resource_identifier, *args, **kwargs) # Update client.resources.delete(id=resource_identifier) # Delete client.resources.list() # List all resources, max 20 at a time ``` -------------------------------- ### Generate Full XML Response Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/api-reference/plivoxml.md Example demonstrating the generation of a complete Plivo XML response, including Speak and GetDigits elements, and converting it to a string. ```python from plivo import plivoxml response = plivoxml.ResponseElement() response.add_speak('Hello, welcome to our service') response.add_get_digits( action='https://example.com/digits', num_digits=1, finish_on_key='#' ) print(response.to_string()) ``` -------------------------------- ### Resource CRUD Operations Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/README.md Demonstrates the standard Create, Read (Get), Update, Delete, and List operations for resources within the Plivo SDK. Includes auto-paginated iteration. ```python # Create resource = client.resources.create(...) # Get (retrieve) resource = client.resources.get(id) # Update resource = client.resources.update(id, ...) # Delete client.resources.delete(id) # List resources = client.resources.list() # Iterate (auto-paginated) for resource in client.resources: print(resource.id) ``` -------------------------------- ### Accessing Pagination Metadata Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/types.md Example of how to access pagination metadata after listing calls. It demonstrates printing the page size, total count, and offset from the meta object. ```python calls = client.calls.list(limit=20, offset=0) print(f"Page size: {calls.meta.limit}") print(f"Total: {calls.meta.total_count}") print(f"Offset: {calls.meta.offset}") ``` -------------------------------- ### Configure Call Recording Format Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/configuration.md Start call recording and specify the desired file format, such as MP3 or WAV. This allows you to choose the most suitable format for your needs. ```python response = client.calls.start_recording( call_uuid, file_format='mp3' # or 'wav' ) ``` -------------------------------- ### Update or Delete a Resource Directly Source: https://github.com/plivo/plivo-python/blob/master/README.md After retrieving a resource using 'get', you can directly call 'update' or 'delete' methods on the resource object itself. ```python resource = client.resources.get(id=resource_identifier) resource.update(*args, **kwargs) # update the resource resource.delete() # Delete the resource ``` -------------------------------- ### AuthenticationError Examples Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/errors.md Raised when authentication fails or credentials are invalid. This can occur due to missing or incorrect credentials, or invalid auth_id format. ```python # Missing credentials client = plivo.RestClient() # Raises AuthenticationError ``` ```python # Invalid auth_id client = plivo.RestClient(auth_id='invalid', auth_token='token') # Raises AuthenticationError ``` ```python # Wrong credentials at API try: client = plivo.RestClient(auth_id='MA123456789012345678', auth_token='wrong') client.calls.get('uuid') # Raises AuthenticationError except AuthenticationError: pass ``` -------------------------------- ### Pagination with Limit and Offset Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/configuration.md Control pagination for API list requests by specifying 'limit' for the number of items per page and 'offset' for the starting point. ```python # First page (default) calls = client.calls.list() # With explicit limit and offset calls = client.calls.list(limit=20, offset=0) # Get second page calls = client.calls.list(limit=20, offset=20) ``` -------------------------------- ### Call Instance Methods Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/api-reference/calls.md Call instances provide direct access to call management methods using their own `call_uuid`. This includes starting and stopping recordings, playing audio, speaking text, and hanging up. ```APIDOC ## Call Instance Methods ### Description Call instances provide direct access to call management methods using their own `call_uuid`. This includes starting and stopping recordings, playing audio, speaking text, and hanging up. ### Methods - `record()`: Starts recording the call. - `speak(text)`: Plays the given text to the call. - `hangup()`: Hangs up the call. ### Example ```python call = client.calls.get('call-uuid') call.record() # Record this call call.speak('Hello') # Speak to this call call.hangup() # Hangup this call ``` ``` -------------------------------- ### Start Call Recording Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/api-reference/calls.md Initiate recording for an active call. You can specify the file format, time limit, and transcription options. Recording completion can be notified via a callback URL. ```python Calls.start_recording(call_uuid, time_limit=None, file_format=None, transcription_type=None, transcription_url=None, transcription_method=None, transcription_report_type=None, callback_url=None, callback_method=None) ``` ```python response = client.calls.start_recording( 'call-uuid', file_format='mp3' ) ``` -------------------------------- ### ResourceNotFoundError Examples Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/errors.md Raised when the requested resource does not exist, typically indicated by an HTTP 404 response. Use this to handle cases where a call, message, or account UUID is not found. ```python from plivo.exceptions import ResourceNotFoundError try: client.calls.get('nonexistent-call-uuid') except ResourceNotFoundError: print("Call not found") ``` ```python try: client.messages.get('nonexistent-message-uuid') except ResourceNotFoundError: print("Message not found") ``` -------------------------------- ### Configure Call Recording with Transcription Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/configuration.md Start call recording and enable transcription using a specified service like AWS. You can also set the transcription URL and method. ```python response = client.calls.start_recording( call_uuid, file_format='mp3', transcription_type='aws', # or other services transcription_url='https://example.com/transcription', transcription_method='POST' ) ``` -------------------------------- ### Generate Plivo XML for Text-to-Speech Source: https://github.com/plivo/plivo-python/blob/master/README.md Create Plivo XML dynamically using the 'plivoxml' module. This example generates XML to make Plivo speak a message. The 'to_string()' method converts the XML object into its string representation. ```python from plivo import plivoxml xml_response = plivoxml.ResponseElement() xml_response.add_speak('Hello, world!') # or add(plivoxml.SpeakElement(text)) print(xml_response.to_string()) ``` -------------------------------- ### Generate JWT Access Token Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/README.md Create a JSON Web Token (JWT) for authenticating with Plivo endpoints. This example generates a token with voice grants and sets its validity period. ```python from plivo.utils import jwt import time token = jwt.AccessToken( auth_id='MA123456789012345678', auth_token='your_token', username='user@example.com', valid_from=int(time.time()), lifetime=300 ) token.add_voice_grants(incoming=True, outgoing=True) jwt_string = token.to_jwt() ``` -------------------------------- ### Get Plivo SDK Version Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/configuration.md Retrieve the currently installed version of the Plivo Python SDK. This is useful for debugging and ensuring compatibility. ```python from plivo.version import __version__ print(f"Plivo SDK version: {__version__}") ``` -------------------------------- ### Generate Plivo XML Response Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/README.md Create a Plivo XML response object to control call flow. This example adds a 'speak' command and a 'get digits' command. ```python from plivo import plivoxml response = plivoxml.ResponseElement() response.add_speak('Hello, welcome to our service') response.add_get_digits( action='https://example.com/process', num_digits=1 ) print(response.to_string()) ``` -------------------------------- ### List Recordings with Pagination Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/api-reference/recordings.md Demonstrates how to list recordings using limit and offset for pagination. It also shows how to access total count and iterate through recordings using auto-pagination. ```python # Get first page page1 = client.recordings.list(limit=20, offset=0) print(f"Found {len(page1)} recordings on page 1") print(f"Total: {page1.meta.total_count}") # Get second page page2 = client.recordings.list(limit=20, offset=20) # Or use auto-pagination for recording in client.recordings: print(f"{recording.recording_id}: {recording.duration}s") ``` -------------------------------- ### Python Usage with Environment Variables Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/configuration.md Demonstrates how to set environment variables in Python and initialize RestClient, which will automatically pick them up. ```python import os os.environ['PLIVO_AUTH_ID'] = 'MA123456789012345678' os.environ['PLIVO_AUTH_TOKEN'] = 'your_token_here' client = plivo.RestClient() # Reads from env vars ``` -------------------------------- ### Initialize REST Client Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/README.md Instantiate the standard REST API client for Plivo. Provide authentication credentials via environment variables or constructor parameters. ```python import plivo client = plivo.RestClient(auth_id='...', auth_token='...') ``` -------------------------------- ### List Recordings with Pagination Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/api-reference/recordings.md Demonstrates how to list recordings and handle pagination. ```APIDOC ## List Recordings with Pagination ### Description Retrieves a list of call recordings, supporting manual pagination and auto-pagination. ### Method `client.recordings.list()` ### Parameters #### Query Parameters - **`limit`** (integer) - Optional - The number of recordings to return per page. - **`offset`** (integer) - Optional - The number of recordings to skip before starting to collect the result set. ### Request Example (Manual Pagination) ```python # Get first page page1 = client.recordings.list(limit=20, offset=0) print(f"Found {len(page1)} recordings on page 1") print(f"Total: {page1.meta.total_count}") # Get second page page2 = client.recordings.list(limit=20, offset=20) ``` ### Request Example (Auto-Pagination) ```python # Iterate through all recordings using auto-pagination for recording in client.recordings: print(f"{recording.recording_id}: {recording.duration}s") ``` ### Response #### Success Response (200) - **`recording_id`** (string) - The unique identifier for the recording. - **`duration`** (string) - The duration of the recording in seconds. - **`meta`** (object) - Metadata about the pagination. - **`total_count`** (integer) - The total number of recordings available. ``` -------------------------------- ### Create a Voice Application Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/api-reference/applications.md Configures a new application specifically for handling incoming calls. Requires an application name and an answer URL. ```python voice_app = client.applications.create( app_name='Voice Handler', answer_url='https://example.com/answer', hangup_url='https://example.com/hangup' ) ``` -------------------------------- ### Basic RestClient Configuration Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/configuration.md Initialize RestClient by providing auth_id and auth_token directly as constructor parameters. ```python import plivo client = plivo.RestClient( auth_id='MA123456789012345678', auth_token='your_auth_token_here' ) ``` -------------------------------- ### Initialize RestClient with Environment Variables Source: https://github.com/plivo/plivo-python/blob/master/README.md Initialize the RestClient without arguments to automatically fetch authentication credentials from PLIVO_AUTH_ID and PLIVO_AUTH_TOKEN environment variables. This is the recommended approach to avoid committing credentials to source control. ```python import plivo client = plivo.RestClient() ``` -------------------------------- ### Get Verification Session Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/api-reference/verify-sessions.md Retrieves the details of a specific verification session using its unique session UUID. ```APIDOC ## GET /v1/verify/session/{session_uuid} ### Description Retrieve a verification session. ### Method GET ### Endpoint /v1/verify/session/{session_uuid} ### Parameters #### Path Parameters - **session_uuid** (str) - Required - UUID of the session ### Response #### Success Response (200) - **session_uuid** (str) - Session identifier - **status** (str) - Session status: 'in-progress', 'expired', or 'verified' - **recipient** (str) - Phone number being verified - **channel** (str) - Delivery channel: 'sms' or 'voice' - **created_at** (str) - Creation timestamp - **app_uuid** (str) - Associated application UUID - **app_hash** (str) - Android app hash if applicable ### Response Example ```json { "session_uuid": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "status": "in-progress", "recipient": "14155551234", "channel": "sms", "created_at": "2023-10-27T10:00:00Z", "app_uuid": "app-uuid-here", "app_hash": "app-hash-here" } ``` ``` -------------------------------- ### Get a PHLO by ID (Collection) Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/api-reference/phlo.md Retrieve a PHLO object using its ID from the Phlos collection interface. ```python phlo = phlo_client.phlo.get('your-phlo-id') ``` -------------------------------- ### HTTP Methods Enum Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/types.md Defines the supported HTTP methods for API requests. Currently, GET and POST are listed. ```python http_method = 'GET' | 'POST' ``` -------------------------------- ### Make a Call Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/README.md Illustrates how to initiate a voice call using the Plivo Python SDK. It involves creating a `RestClient` instance and then using the `calls.create` method, specifying the 'from' and 'to' numbers, and the 'answer_url'. ```APIDOC ## Make a Call ### Description This operation initiates a voice call using the Plivo Python SDK. It requires initializing the `RestClient` and then calling the `calls.create` method with the source number, destination number, and the URL to fetch call control XML. ### Method `client.calls.create(...) ### Parameters - **from_** (string) - Required - The originating phone number. - **to_** (string) - Required - The destination phone number. - **answer_url** (string) - Required - The URL Plivo will fetch to get instructions for the call. ### Request Example ```python import plivo client = plivo.RestClient() call = client.calls.create( from_='14155551234', to_='14155555678', answer_url='https://example.com/answer' ) print(f"Call initiated: {call.call_uuid}") ``` ### Response - **call_uuid** (string) - The unique identifier for the initiated call. ``` -------------------------------- ### Initialize PHLO Client Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/README.md Instantiate the PHLO API client for Plivo. Authentication credentials can be provided similarly to the REST client. ```python import plivo phlo_client = plivo.phlo.RestClient(auth_id='...', auth_token='...') ``` -------------------------------- ### Initialize RestClient Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/api-reference/rest-client.md Instantiate the RestClient using environment variables or explicit credentials. The client can also be used as a context manager. ```python import plivo # Using environment variables client = plivo.RestClient() # Using explicit credentials client = plivo.RestClient(auth_id='your_auth_id', auth_token='your_auth_token') # Using context manager with plivo.RestClient() as client: # Client resources available here pass ``` -------------------------------- ### Retrieve a PHLO by ID Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/api-reference/phlo.md Get a specific PHLO object using its unique ID. This is necessary before running a PHLO. ```python phlo = phlo_client.phlo.get('phlo-id-from-console') print(phlo.name) ``` -------------------------------- ### Create a Messaging Application Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/api-reference/applications.md Configures a new application for handling incoming SMS messages. Requires an application name and a message URL. ```python sms_app = client.applications.create( app_name='SMS Handler', message_url='https://example.com/messages' ) ``` -------------------------------- ### RestClient Constructor Parameters Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/configuration.md Initialize RestClient with authentication credentials, proxies, and timeout. Credentials can be read from environment variables if not provided. ```python RestClient(auth_id=None, auth_token=None, proxies=None, timeout=5) ``` -------------------------------- ### Create New Subaccount Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/api-reference/accounts.md Creates a new subaccount with a specified name and an option to enable it immediately. The `client` must be initialized. ```python subaccount = client.subaccounts.create( name='My Subaccount', enabled=True ) print(f"Subaccount ID: {subaccount.auth_id}") ``` -------------------------------- ### Get PHLO by ID Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/api-reference/phlo.md Retrieves a specific PHLO workflow by its unique identifier. This method is part of the Phlos resource interface. ```APIDOC ## Method: get (Phlos) Get a PHLO by ID. ### Method Signature ```python Phlos.get(phlo_id) ``` #### Parameters - **phlo_id** (str) - Required - PHLO ID. #### Returns - `Phlo` object #### Example ```python phlo = phlo_client.phlo.get('your-phlo-id') ``` ``` -------------------------------- ### create Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/api-reference/applications.md Create a new application with specified details for handling voice calls and messages. ```APIDOC ## create ### Description Create a new application. ### Method POST (inferred from SDK usage) ### Endpoint /v1/Account/{Account_id}/Application/ ### Parameters #### Path Parameters - **Account_id** (str) - Required - Your Plivo API authentication ID #### Query Parameters - **app_name** (str) - Required - Application name - **answer_url** (str) - Optional - Webhook URL for incoming calls - **answer_method** (str) - Optional - HTTP method: 'GET' or 'POST'. Default: 'POST' - **hangup_url** (str) - Optional - Webhook for call hangup - **hangup_method** (str) - Optional - HTTP method for hangup_url. Default: 'POST' - **fallback_answer_url** (str) - Optional - Fallback URL if answer_url fails - **fallback_method** (str) - Optional - HTTP method for fallback_url. Default: 'POST' - **message_url** (str) - Optional - Webhook for incoming messages - **message_method** (str) - Optional - HTTP method for message_url. Default: 'POST' - **default_number_app** (bool) - Optional - Make default for phone numbers. Default: False - **default_endpoint_app** (bool) - Optional - Make default for endpoints. Default: False - **subaccount** (str) - Optional - Subaccount to own application - **log_incoming_messages** (bool) - Optional - Log incoming message content. Default: True - **public_uri** (bool) - Optional - Public URI setting - **callback_url** (str) - Optional - Async callback URL - **callback_method** (str) - Optional - HTTP method for callback ### Request Example ```python import plivo client = plivo.RestClient() app = client.applications.create( app_name='My Voice App', answer_url='https://example.com/answer', answer_method='POST', hangup_url='https://example.com/hangup', message_url='https://example.com/messages' ) print(f"Application ID: {app.app_id}") ``` ### Response #### Success Response (200) - **Application** (object) - Application object with `app_id` #### Response Example { "app_id": "some_app_id" } ``` -------------------------------- ### Create a Hybrid Application Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/api-reference/applications.md Configures a new application to handle both incoming calls and messages. Requires an application name, an answer URL, and a message URL. ```python hybrid_app = client.applications.create( app_name='Hybrid Handler', answer_url='https://example.com/answer', message_url='https://example.com/messages' ) ``` -------------------------------- ### Initialize RestClient using a Context Manager Source: https://github.com/plivo/plivo-python/blob/master/README.md Use a context manager to initialize the RestClient, which automatically frees all resources used by the client upon exiting the 'with' block. This is useful for on-demand client creation. ```python import plivo with plivo.RestClient() as client: pass # Do something with the client ``` -------------------------------- ### Initialize PHLO RestClient Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/api-reference/phlo.md Instantiate the PHLO RestClient. It can read credentials from environment variables or accept them directly. ```python import plivo phlo_client = plivo.phlo.RestClient() # or phlo_client = plivo.phlo.RestClient( auth_id='your_auth_id', auth_token='your_auth_token' ) ``` -------------------------------- ### Get Media for a Message Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/api-reference/messages.md Retrieve a list of media items associated with a specific message. This method is called on a Message object after it has been retrieved. ```python Message.listMedia() ``` ```python message = client.messages.get('message-uuid') media = message.listMedia() ``` -------------------------------- ### get Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/api-reference/messages.md Retrieve a specific message using its unique identifier. This method allows fetching the status and details of a previously sent message. ```APIDOC ## GET /messages/{message_uuid} ### Description Retrieve a specific message using its unique identifier. This method allows fetching the status and details of a previously sent message. ### Method GET ### Endpoint /messages/{message_uuid} ### Parameters #### Path Parameters - **message_uuid** (str) - Required - UUID of the message to retrieve ### Response #### Success Response (200) - **message_state** (str) - The current state of the message (e.g., 'sent', 'delivered', 'failed'). #### Response Example ```json { "message_state": "sent" } ``` ### Error Handling - **ResourceNotFoundError**: If message not found ``` -------------------------------- ### Get Verify Session Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/api-reference/verify-sessions.md Retrieves a specific verify session by its UUID. This operation allows you to fetch the current status, recipient, and channel of a session. ```APIDOC ## GET /verify_session/{session_uuid} ### Description Retrieves a specific verify session using its unique identifier. ### Method GET ### Endpoint /verify_session/{session_uuid} ### Parameters #### Path Parameters - **session_uuid** (string) - Required - The unique identifier of the session to retrieve. ### Response #### Success Response (200) - **status** (string) - The current status of the session. - **recipient** (string) - The recipient of the verification. - **channel** (string) - The channel used for verification (e.g., SMS, Voice). ### Request Example ```python session = client.verify_session.get('session-uuid') print(f"Status: {session.status}") print(f"Recipient: {session.recipient}") print(f"Channel: {session.channel}") ``` ``` -------------------------------- ### Initialize RestClient with Explicit Credentials Source: https://github.com/plivo/plivo-python/blob/master/README.md Initialize the RestClient by explicitly providing your authentication ID and token. Use this method if you are not using environment variables. ```python import plivo client = plivo.RestClient(auth_id='your_auth_id', auth_token='your_auth_token') ``` -------------------------------- ### Get Call Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/api-reference/calls.md Retrieves the details of a specific call using its unique UUID. This is useful for checking the status or other attributes of an ongoing or completed call. ```APIDOC ## GET /calls/{call_uuid} ### Description Retrieve details of a specific call. ### Method GET ### Endpoint /calls/{call_uuid} ### Parameters #### Path Parameters - **call_uuid** (str) - Yes - UUID of the call ### Response #### Success Response (200) - **call_state** (str) - The current state of the call. ### Response Example ```json { "call_uuid": "call-uuid-here", "call_state": "completed" } ``` ``` -------------------------------- ### Set Authentication via Environment Variables Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/README.md Configure Plivo SDK authentication by setting PLIVO_AUTH_ID and PLIVO_AUTH_TOKEN environment variables. This is the recommended method. ```bash export PLIVO_AUTH_ID='MA123456789012345678' export PLIVO_AUTH_TOKEN='your_token' ``` -------------------------------- ### Send Interactive List Message Source: https://github.com/plivo/plivo-python/blob/master/README.md Use this snippet to send an interactive list message with options to the user. Ensure you have the Plivo SDK installed and authenticated. ```python import plivo from plivo.utils.interactive import Interactive client = plivo.RestClient('','') interactive=Interactive(**{ "type": "list", "header": { "type": "text", "text": "Welcome to Plivo" }, "body": { "text": "You can review the list of rewards we offer" }, "footer": { "text": "Yours Truly" }, "action": { "buttons": [{ "title": "Click here" }], "sections": [ { "title": "SECTION_1_TITLE", "rows": [ { "id": "SECTION_1_ROW_1_ID", "title": "SECTION_1_ROW_1_TITLE", "description": "SECTION_1_ROW_1_DESCRIPTION" }, { "id": "SECTION_1_ROW_2_ID", "title": "SECTION_1_ROW_2_TITLE", "description": "SECTION_1_ROW_2_DESCRIPTION" } ] }, { "title": "SECTION_2_TITLE", "rows": [ { "id": "SECTION_2_ROW_1_ID", "title": "SECTION_2_ROW_1_TITLE", "description": "SECTION_2_ROW_1_DESCRIPTION" }, { "id": "SECTION_2_ROW_2_ID", "title": "SECTION_2_ROW_2_TITLE", "description": "SECTION_2_ROW_2_DESCRIPTION" } ] } ] } }) response= client.messages.create( src="the_from_number", dst="the_to_number", type_="whatsapp", interactive=interactive ) print(response) ``` -------------------------------- ### PHLO Client Constructor Parameters Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/configuration.md Initialize the PHLO client using the same parameters as RestClient: auth_id, auth_token, proxies, and timeout. ```python phlo.RestClient(auth_id=None, auth_token=None, proxies=None, timeout=5) ``` -------------------------------- ### is_valid_subaccount Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/api-reference/utilities.md Checks if a given authentication ID is in the valid subaccount format. A valid subaccount ID is a string of exactly 20 characters starting with 'SA'. ```APIDOC ## Function: is_valid_subaccount ### Description Check if auth_id is valid subaccount format. ### Signature ```python is_valid_subaccount(subaccount) ``` ### Parameters #### Path Parameters - **subaccount** (str) - Required - The authentication ID to validate ### Returns `bool` — True if the auth_id is a valid subaccount format, False otherwise ### Criteria String of exactly 20 characters starting with 'SA' ``` -------------------------------- ### Run a PHLO Source: https://github.com/plivo/plivo-python/blob/master/README.md Execute a pre-configured PHLO using its ID. Ensure you have your authentication credentials and the PHLO ID. ```python import plivo auth_id = '' auth_token = '' phlo_id = '','') template=Template(**{ "name": "template_name", "language": "en_US", "components": [ { "type": "header", "parameters": [ { "type": "text", "parameter_name": "header_title", "text": "WA-header" } ] }, { "type": "body", "parameters": [ { "type": "text", "parameter_name": "user_name", "text": "Saurabh" } ] } ] }) response= client.messages.create( src="the_from_number", dst="the_to_number", type_="whatsapp", template=template ) print(response) ``` -------------------------------- ### RestClient Constructor Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/api-reference/phlo.md Initializes the PHLO RestClient. This is the entry point for interacting with the PHLO API. It can be initialized with or without authentication credentials, falling back to environment variables if not provided. ```APIDOC ## Class: RestClient (PHLO) **Module**: `plivo.phlo.RestClient` The entry point for the PHLO API, used to run and manage PHLO workflows. ### Constructor ```python phlo.RestClient(auth_id=None, auth_token=None, proxies=None, timeout=5) ``` #### Parameters - **auth_id** (str) - Optional - Plivo auth ID. Reads from `PLIVO_AUTH_ID` if not provided. - **auth_token** (str) - Optional - Plivo auth token. Reads from `PLIVO_AUTH_TOKEN` if not provided. - **proxies** (dict) - Optional - HTTP proxy configuration. - **timeout** (int) - Optional - Request timeout in seconds (Default: 5). #### Returns - PHLO RestClient instance #### Example ```python import plivo phlo_client = plivo.phlo.RestClient() # or phlo_client = plivo.phlo.RestClient( auth_id='your_auth_id', auth_token='your_auth_token' ) ``` ``` -------------------------------- ### Handle Plivo SDK Errors Source: https://github.com/plivo/plivo-python/blob/master/_autodocs/README.md Catch specific Plivo SDK exceptions like AuthenticationError, ValidationError, ResourceNotFoundError, PlivoServerError, and ForbiddenError. Provides examples for handling validation and server errors. ```python from plivo.exceptions import ( AuthenticationError, ValidationError, ResourceNotFoundError, PlivoServerError, ForbiddenError ) try: client.calls.create(...) except ValidationError as e: print(f"Invalid input: {e}") except ResourceNotFoundError: print("Resource not found") except PlivoServerError: print("Server error - retry later") ```