# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations from typing import Dict, Union, Iterable from typing_extensions import Literal import httpx from ...types import ( StreamCodec, StreamBidirectionalMode, StreamBidirectionalCodec, StreamBidirectionalTargetLegs, StreamBidirectionalSamplingRate, call_dial_params, ) from .actions import ( ActionsResource, AsyncActionsResource, ActionsResourceWithRawResponse, AsyncActionsResourceWithRawResponse, ActionsResourceWithStreamingResponse, AsyncActionsResourceWithStreamingResponse, ) from ..._types import Body, Omit, Query, Headers, NotGiven, SequenceNotStr, omit, not_given from ..._utils import path_template, maybe_transform, async_maybe_transform from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import ( to_raw_response_wrapper, to_streamed_response_wrapper, async_to_raw_response_wrapper, async_to_streamed_response_wrapper, ) from ..._base_client import make_request_options from ...types.stream_codec import StreamCodec from ...types.sip_header_param import SipHeaderParam from ...types.call_dial_response import CallDialResponse from ...types.custom_sip_header_param import CustomSipHeaderParam from ...types.dialogflow_config_param import DialogflowConfigParam from ...types.sound_modifications_param import SoundModificationsParam from ...types.stream_bidirectional_mode import StreamBidirectionalMode from ...types.stream_bidirectional_codec import StreamBidirectionalCodec from ...types.call_assistant_request_param import CallAssistantRequestParam from ...types.call_retrieve_status_response import CallRetrieveStatusResponse from ...types.stream_bidirectional_target_legs import StreamBidirectionalTargetLegs from ...types.stream_bidirectional_sampling_rate import StreamBidirectionalSamplingRate from ...types.calls.transcription_start_request_param import TranscriptionStartRequestParam from ...types.conversation_relay_embedded_config_param import ConversationRelayEmbeddedConfigParam __all__ = ["CallsResource", "AsyncCallsResource"] class CallsResource(SyncAPIResource): @cached_property def actions(self) -> ActionsResource: """Call Control command operations""" return ActionsResource(self._client) @cached_property def with_raw_response(self) -> CallsResourceWithRawResponse: """ This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/team-telnyx/telnyx-python#accessing-raw-response-data-eg-headers """ return CallsResourceWithRawResponse(self) @cached_property def with_streaming_response(self) -> CallsResourceWithStreamingResponse: """ An alternative to `.with_raw_response` that doesn't eagerly read the response body. For more information, see https://www.github.com/team-telnyx/telnyx-python#with_streaming_response """ return CallsResourceWithStreamingResponse(self) def dial( self, *, connection_id: str, from_: str, to: Union[str, SequenceNotStr[str]], answering_machine_detection: Literal[ "premium", "premium_ios_call_screening_detection", "detect", "detect_beep", "detect_words", "greeting_end", "disabled", ] | Omit = omit, answering_machine_detection_config: call_dial_params.AnsweringMachineDetectionConfig | Omit = omit, assistant: CallAssistantRequestParam | Omit = omit, audio_url: str | Omit = omit, billing_group_id: str | Omit = omit, bridge_intent: bool | Omit = omit, bridge_on_answer: bool | Omit = omit, client_state: str | Omit = omit, command_id: str | Omit = omit, conference_config: call_dial_params.ConferenceConfig | Omit = omit, conversation_relay_config: ConversationRelayEmbeddedConfigParam | Omit = omit, custom_headers: Iterable[CustomSipHeaderParam] | Omit = omit, deepfake_detection: call_dial_params.DeepfakeDetection | Omit = omit, dialogflow_config: DialogflowConfigParam | Omit = omit, diversion: str | Omit = omit, enable_dialogflow: bool | Omit = omit, from_display_name: str | Omit = omit, link_to: str | Omit = omit, media_encryption: Literal["disabled", "SRTP", "DTLS"] | Omit = omit, media_name: str | Omit = omit, park_after_unbridge: str | Omit = omit, preferred_codecs: str | Omit = omit, prevent_double_bridge: bool | Omit = omit, privacy: Literal["id", "none"] | Omit = omit, record: Literal["record-from-answer"] | Omit = omit, record_channels: Literal["single", "dual"] | Omit = omit, record_custom_file_name: str | Omit = omit, record_format: Literal["wav", "mp3"] | Omit = omit, record_max_length: int | Omit = omit, record_timeout_secs: int | Omit = omit, record_track: Literal["both", "inbound", "outbound"] | Omit = omit, record_trim: Literal["trim-silence"] | Omit = omit, retry_on_timeout: bool | Omit = omit, route_to_mobile: bool | Omit = omit, send_digits_on_answer: str | Omit = omit, send_silence_when_idle: bool | Omit = omit, sip_auth_password: str | Omit = omit, sip_auth_username: str | Omit = omit, sip_headers: Iterable[SipHeaderParam] | Omit = omit, sip_region: Literal["US", "Europe", "Canada", "Australia", "Middle East"] | Omit = omit, sip_transport_protocol: Literal["UDP", "TCP", "TLS"] | Omit = omit, sound_modifications: SoundModificationsParam | Omit = omit, stream_auth_token: str | Omit = omit, stream_bidirectional_codec: StreamBidirectionalCodec | Omit = omit, stream_bidirectional_mode: StreamBidirectionalMode | Omit = omit, stream_bidirectional_sampling_rate: StreamBidirectionalSamplingRate | Omit = omit, stream_bidirectional_target_legs: StreamBidirectionalTargetLegs | Omit = omit, stream_codec: StreamCodec | Omit = omit, stream_establish_before_call_originate: bool | Omit = omit, stream_track: Literal["inbound_track", "outbound_track", "both_tracks"] | Omit = omit, stream_url: str | Omit = omit, supervise_call_control_id: str | Omit = omit, supervisor_role: Literal["barge", "whisper", "monitor"] | Omit = omit, time_limit_secs: int | Omit = omit, timeout_secs: int | Omit = omit, transcription: bool | Omit = omit, transcription_config: TranscriptionStartRequestParam | Omit = omit, webhook_retries_policies: Dict[str, call_dial_params.WebhookRetriesPolicies] | Omit = omit, webhook_url: str | Omit = omit, webhook_url_method: Literal["POST", "GET"] | Omit = omit, webhook_urls: Dict[str, SequenceNotStr[str]] | Omit = omit, webhook_urls_method: Literal["POST", "GET"] | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> CallDialResponse: """Dial a number or SIP URI from a given connection. A successful response will include a `call_leg_id` which can be used to correlate the command with subsequent webhooks. To place the call with an AI assistant from the start, include `assistant.id` and any per-call overrides in the `assistant` object; Telnyx attempts to warm up the assistant before placing the call and starts it automatically when the called party answers. **Expected Webhooks:** - `call.initiated` - `call.answered` or `call.hangup` - `call.conversation.created` when the requested assistant conversation is created, or `call.conversation.start_failed` when it could not be started after the called party answered - `call.hold` and `call.unhold` if the call is held/unheld - `call.machine.detection.ended` if `answering_machine_detection` was requested - `call.machine.greeting.ended` if `answering_machine_detection` was requested to detect the end of machine greeting - `call.machine.premium.detection.ended` if `answering_machine_detection=premium` was requested - `call.machine.premium.greeting.ended` if `answering_machine_detection=premium` was requested and a beep was detected - `call.machine.premium.call_screening.detected` if `answering_machine_detection=premium_ios_call_screening_detection` was requested and an Apple Call Screening tone was detected - `call.deepfake_detection.result` if `deepfake_detection` was enabled - `call.deepfake_detection.error` if `deepfake_detection` was enabled and an error occurred - `streaming.started`, `streaming.stopped` or `streaming.failed` if `stream_url` was set When the `record` parameter is set to `record-from-answer`, the response will include a `recording_id` field. Args: connection_id: The ID of the Call Control App (formerly ID of the connection) to be used when dialing the destination. from_: The `from` number to be used as the caller id presented to the destination (`to` number). The number should be in +E164 format. to: The DID or SIP URI to dial out to. Multiple DID or SIP URIs can be provided using an array of strings. For SIP URI destinations, append `;secure=true` or `;secure=srtp` to enable SRTP media encryption for that endpoint, or `;secure=dtls` to enable DTLS media encryption for that endpoint. If `media_encryption` is set to `SRTP` or `DTLS`, it takes precedence over any per-endpoint `secure` URI parameter. For a single string destination, you may append a comma followed by DTMF digits (e.g. `+18004247767,200`) to play those digits as DTMF once the called party answers — equivalent to setting `send_digits_on_answer` separately. If both are present, the explicit `send_digits_on_answer` parameter takes precedence. This shorthand is not supported when `to` is an array. answering_machine_detection: Enables Answering Machine Detection. Telnyx offers Premium and Standard detections. With Premium detection, when a call is answered, Telnyx runs real-time detection and sends a `call.machine.premium.detection.ended` webhook with one of the following results: `human_residence`, `human_business`, `machine`, `silence` or `fax_detected`. If we detect a beep, we also send a `call.machine.premium.greeting.ended` webhook with the result of `beep_detected`. If we detect a beep before `call.machine.premium.detection.ended` we only send `call.machine.premium.greeting.ended`, and if we detect a beep after `call.machine.premium.detection.ended`, we send both webhooks. With Standard detection, when a call is answered, Telnyx runs real-time detection to determine if it was picked up by a human or a machine and sends an `call.machine.detection.ended` webhook with the analysis result. If `greeting_end` or `detect_words` is used and a `machine` is detected, you will receive another `call.machine.greeting.ended` webhook when the answering machine greeting ends with a beep or silence. If `detect_beep` is used, you will only receive `call.machine.greeting.ended` if a beep is detected. If `answering_machine_detection` is set to `premium_ios_call_screening_detection`, Premium AMD runs with iOS Call Screening support: after an initial `machine` result, Telnyx listens for the iOS call-screening prompt to end or for an Apple Call Screening tone, sends `call.machine.premium.greeting.ended` with `result=prompt_ended` or `call.machine.premium.call_screening.detected` with `result=screening` respectively. When the Apple Call Screening tone is detected, Premium AMD is restarted on the screened call and a `call.machine.premium.detection.ended` webhook with the post-screening classification follows. answering_machine_detection_config: Optional configuration parameters to modify 'answering_machine_detection' performance. Only `total_analysis_time_millis` and `greeting_duration_millis` parameters are applicable when `premium` is selected as answering_machine_detection. `prompt_end_timeout_millis` is additionally applicable when `premium_ios_call_screening_detection` is selected. assistant: AI Assistant configuration and per-call overrides. All fields except `id` are optional. Omitted assistant fields use the stored configuration. Supplied `voice_settings` and `transcription` objects replace their stored objects rather than merging individual settings; include every setting you want to retain. `dynamic_variables` are merged, with request values taking precedence. audio_url: The URL of a file to be played back to the callee when the call is answered. The URL can point to either a WAV or MP3 file. media_name and audio_url cannot be used together in one request. billing_group_id: Use this field to set the Billing Group ID for the call. Must be a valid and existing Billing Group ID. bridge_intent: Indicates the intent to bridge this call with the call specified in link_to. When bridge_intent is true, link_to becomes required and the from number will be overwritten by the from number from the linked call. bridge_on_answer: Whether to automatically bridge answered call to the call specified in link_to. When bridge_on_answer is true, link_to becomes required. client_state: Use this field to add state to every subsequent webhook. It must be a valid Base-64 encoded string. command_id: Use this field to avoid duplicate commands. Telnyx will ignore others Dial commands with the same `command_id`. conference_config: Optional configuration parameters to dial new participant into a conference. conversation_relay_config: Starts a Conversation Relay session automatically when the answered/dialed call is answered. This embedded shape is supported on `answer` and `dial`. It uses public field names (`url`, `dtmf_detection`, `greeting`, `voice`, `language`, etc.) and maps them to the underlying Conversation Relay action. `client_state`, `tts_language`, and `transcription_language` inside this object are ignored; use the parent command's `client_state` and `command_id` fields instead. custom_headers: Custom headers to be added to the SIP INVITE. deepfake_detection: Enables deepfake detection on the call. When enabled, audio from the remote party is streamed to a detection service that analyzes whether the voice is AI-generated. Results are delivered via the `call.deepfake_detection.result` webhook. diversion: The `to` number of an active inbound call, in +E164 format. Telnyx checks whether there is currently an active inbound call where `to` matches this `diversion` value and `from` matches the `from` number supplied for this request. If such a call exists, the `from` number is treated as verified (since it is already on an active inbound call to you) and can be used as the caller id for this outbound call. enable_dialogflow: Enables Dialogflow for the current call. The default value is false. from_display_name: The `from_display_name` string to be used as the caller id name (SIP From Display Name) presented to the destination (`to` number). The string should have a maximum of 128 characters, containing only letters, numbers, spaces, and -\\__~!.+ special characters. If ommited, the display name will be the same as the number in the `from` field. link_to: Use another call's control id for sharing the same call session id media_encryption: Defines whether media should be encrypted on the call. For SIP URI destinations, media encryption can also be requested per endpoint with the `secure` URI parameter: `;secure=true` or `;secure=srtp` enables SRTP, and `;secure=dtls` enables DTLS. This parameter, when set to `SRTP` or `DTLS`, takes precedence over the per-endpoint `secure` value. media_name: The media_name of a file to be played back to the callee when the call is answered. The media_name must point to a file previously uploaded to api.telnyx.com/v2/media by the same user/organization. The file must either be a WAV or MP3 file. park_after_unbridge: If supplied with the value `self`, the current leg will be parked after unbridge. If not set, the default behavior is to hang up the leg. When park_after_unbridge is set, link_to becomes required. preferred_codecs: The list of comma-separated codecs in a preferred order for the forked media to be received. prevent_double_bridge: Prevents bridging and hangs up the call if the target is already bridged. Disabled by default. privacy: Indicates the privacy level to be used for the call. When set to `id`, caller ID information (name and number) will be hidden from the called party. When set to `none` or omitted, caller ID will be shown normally. record: Start recording automatically after an event. Disabled by default. record_channels: Defines which channel should be recorded ('single' or 'dual') when `record` is specified. record_custom_file_name: The custom recording file name to be used instead of the default `call_leg_id`. Telnyx will still add a Unix timestamp suffix. record_format: Defines the format of the recording ('wav' or 'mp3') when `record` is specified. record_max_length: Defines the maximum length for the recording in seconds when `record` is specified. The minimum value is 0. The maximum value is 43200. The default value is 0 (infinite). record_timeout_secs: The number of seconds that Telnyx will wait for the recording to be stopped if silence is detected when `record` is specified. The timer only starts when the speech is detected. Please note that call transcription is used to detect silence and the related charge will be applied. The minimum value is 0. The default value is 0 (infinite). record_track: The audio track to be recorded. Can be either `both`, `inbound` or `outbound`. If only single track is specified (`inbound`, `outbound`), `channels` configuration is ignored and it will be recorded as mono (single channel). record_trim: When set to `trim-silence`, silence will be removed from the beginning and end of the recording. retry_on_timeout: Whether to keep trying the remaining routing paths (e.g. alternate providers/gateways) for the same destination after `timeout_secs` is reached for the current attempt. When set to `false`, reaching `timeout_secs` aborts the entire dial attempt and the `call.hangup` webhook reports a `hangup_cause` of `no_answer` instead of `timeout`. route_to_mobile: When set to true, routes the call directly to the mobile device associated with the destination Telnyx Mobile number, bypassing Inbound Calls Interception configured in the Telnyx Portal under Mobile Numbers → select the number → Voice → Call Interception. Use this when transferring an intercepted call to the mobile device to prevent the call from being intercepted again. Defaults to false. send_digits_on_answer: DTMF digits to send automatically after the called party answers. Useful for reaching an extension behind an IVR (e.g. `"200"` to dial extension 200 once the called party picks up). Allowed characters: `0-9`, `A-D`, `w` (0.5s pause), `W` (1s pause), `*`, `#`. Maximum 64 characters. When omitted, no automatic DTMF is sent. May also be supplied inline by appending `,` to `to` (e.g. `to=+18004247767,200`); if both forms are present, this explicit field takes precedence. send_silence_when_idle: Generate silence RTP packets when no transmission available. sip_auth_password: SIP Authentication password used for SIP challenges. sip_auth_username: SIP Authentication username used for SIP challenges. sip_headers: SIP headers to be added to the SIP INVITE request. Currently only User-to-User header is supported. sip_region: Defines the SIP region to be used for the call. sip_transport_protocol: Defines SIP transport protocol to be used on the call. sound_modifications: Use this field to modify sound effects, for example adjust the pitch. stream_auth_token: An authentication token to be sent as part of the WebSocket connection when using streaming. Maximum length is 4000 characters. stream_bidirectional_codec: Indicates codec for bidirectional streaming RTP payloads. Used only with stream_bidirectional_mode=rtp. Case sensitive. stream_bidirectional_mode: Configures method of bidirectional streaming (mp3, rtp). stream_bidirectional_sampling_rate: Audio sampling rate. stream_bidirectional_target_legs: Specifies which call legs should receive the bidirectional stream audio. stream_codec: Specifies the codec to be used for the streamed audio. When set to 'default' or when transcoding is not possible, the codec from the call will be used. stream_establish_before_call_originate: Establish websocket connection before dialing the destination. This is useful for cases where the websocket connection takes a long time to establish. stream_track: Specifies which track should be streamed. stream_url: The destination WebSocket address where the stream is going to be delivered. supervise_call_control_id: The call leg which will be supervised by the new call. supervisor_role: The role of the supervisor call. 'barge' means that supervisor call hears and is being heard by both ends of the call (caller & callee). 'whisper' means that only supervised_call_control_id hears supervisor but supervisor can hear everything. 'monitor' means that nobody can hear supervisor call, but supervisor can hear everything on the call. time_limit_secs: Sets the maximum duration of a Call Control Leg in seconds. If the time limit is reached, the call will hangup and a `call.hangup` webhook with a `hangup_cause` of `time_limit` will be sent. For example, by setting a time limit of 120 seconds, a Call Leg will be automatically terminated two minutes after being answered. The default time limit is 14400 seconds or 4 hours and this is also the maximum allowed call length. timeout_secs: The number of seconds that Telnyx will wait for the call to be answered by the destination to which it is being called. If the timeout is reached before an answer is received, the call will hangup and a `call.hangup` webhook with a `hangup_cause` of `timeout` will be sent. Minimum value is 5 seconds. Maximum value is 600 seconds. transcription: Enable transcription upon call answer. The default value is false. webhook_retries_policies: A map of event types to retry policies. Each retry policy contains an array of `retries_ms` specifying the delays between retry attempts in milliseconds. Maximum 5 retries, total delay cannot exceed 60 seconds. webhook_url: Use this field to override the URL for which Telnyx will send subsequent webhooks to for this call. webhook_url_method: HTTP request type used for `webhook_url`. webhook_urls: A map of event types to arrays of webhook URLs. When an event of the specified type occurs, the webhook URLs associated with that event type will be called instead of the default webhook URL. Events not mapped here will use the default webhook URL. webhook_urls_method: HTTP request method to invoke `webhook_urls`. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ return self._post( "/calls", body=maybe_transform( { "connection_id": connection_id, "from_": from_, "to": to, "answering_machine_detection": answering_machine_detection, "answering_machine_detection_config": answering_machine_detection_config, "assistant": assistant, "audio_url": audio_url, "billing_group_id": billing_group_id, "bridge_intent": bridge_intent, "bridge_on_answer": bridge_on_answer, "client_state": client_state, "command_id": command_id, "conference_config": conference_config, "conversation_relay_config": conversation_relay_config, "custom_headers": custom_headers, "deepfake_detection": deepfake_detection, "dialogflow_config": dialogflow_config, "diversion": diversion, "enable_dialogflow": enable_dialogflow, "from_display_name": from_display_name, "link_to": link_to, "media_encryption": media_encryption, "media_name": media_name, "park_after_unbridge": park_after_unbridge, "preferred_codecs": preferred_codecs, "prevent_double_bridge": prevent_double_bridge, "privacy": privacy, "record": record, "record_channels": record_channels, "record_custom_file_name": record_custom_file_name, "record_format": record_format, "record_max_length": record_max_length, "record_timeout_secs": record_timeout_secs, "record_track": record_track, "record_trim": record_trim, "retry_on_timeout": retry_on_timeout, "route_to_mobile": route_to_mobile, "send_digits_on_answer": send_digits_on_answer, "send_silence_when_idle": send_silence_when_idle, "sip_auth_password": sip_auth_password, "sip_auth_username": sip_auth_username, "sip_headers": sip_headers, "sip_region": sip_region, "sip_transport_protocol": sip_transport_protocol, "sound_modifications": sound_modifications, "stream_auth_token": stream_auth_token, "stream_bidirectional_codec": stream_bidirectional_codec, "stream_bidirectional_mode": stream_bidirectional_mode, "stream_bidirectional_sampling_rate": stream_bidirectional_sampling_rate, "stream_bidirectional_target_legs": stream_bidirectional_target_legs, "stream_codec": stream_codec, "stream_establish_before_call_originate": stream_establish_before_call_originate, "stream_track": stream_track, "stream_url": stream_url, "supervise_call_control_id": supervise_call_control_id, "supervisor_role": supervisor_role, "time_limit_secs": time_limit_secs, "timeout_secs": timeout_secs, "transcription": transcription, "transcription_config": transcription_config, "webhook_retries_policies": webhook_retries_policies, "webhook_url": webhook_url, "webhook_url_method": webhook_url_method, "webhook_urls": webhook_urls, "webhook_urls_method": webhook_urls_method, }, call_dial_params.CallDialParams, ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=CallDialResponse, ) def retrieve_status( self, call_control_id: str, *, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> CallRetrieveStatusResponse: """ Returns the status of a call (data is available 10 minutes after call ended). Args: extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not call_control_id: raise ValueError(f"Expected a non-empty value for `call_control_id` but received {call_control_id!r}") return self._get( path_template("/calls/{call_control_id}", call_control_id=call_control_id), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=CallRetrieveStatusResponse, ) class AsyncCallsResource(AsyncAPIResource): @cached_property def actions(self) -> AsyncActionsResource: """Call Control command operations""" return AsyncActionsResource(self._client) @cached_property def with_raw_response(self) -> AsyncCallsResourceWithRawResponse: """ This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/team-telnyx/telnyx-python#accessing-raw-response-data-eg-headers """ return AsyncCallsResourceWithRawResponse(self) @cached_property def with_streaming_response(self) -> AsyncCallsResourceWithStreamingResponse: """ An alternative to `.with_raw_response` that doesn't eagerly read the response body. For more information, see https://www.github.com/team-telnyx/telnyx-python#with_streaming_response """ return AsyncCallsResourceWithStreamingResponse(self) async def dial( self, *, connection_id: str, from_: str, to: Union[str, SequenceNotStr[str]], answering_machine_detection: Literal[ "premium", "premium_ios_call_screening_detection", "detect", "detect_beep", "detect_words", "greeting_end", "disabled", ] | Omit = omit, answering_machine_detection_config: call_dial_params.AnsweringMachineDetectionConfig | Omit = omit, assistant: CallAssistantRequestParam | Omit = omit, audio_url: str | Omit = omit, billing_group_id: str | Omit = omit, bridge_intent: bool | Omit = omit, bridge_on_answer: bool | Omit = omit, client_state: str | Omit = omit, command_id: str | Omit = omit, conference_config: call_dial_params.ConferenceConfig | Omit = omit, conversation_relay_config: ConversationRelayEmbeddedConfigParam | Omit = omit, custom_headers: Iterable[CustomSipHeaderParam] | Omit = omit, deepfake_detection: call_dial_params.DeepfakeDetection | Omit = omit, dialogflow_config: DialogflowConfigParam | Omit = omit, diversion: str | Omit = omit, enable_dialogflow: bool | Omit = omit, from_display_name: str | Omit = omit, link_to: str | Omit = omit, media_encryption: Literal["disabled", "SRTP", "DTLS"] | Omit = omit, media_name: str | Omit = omit, park_after_unbridge: str | Omit = omit, preferred_codecs: str | Omit = omit, prevent_double_bridge: bool | Omit = omit, privacy: Literal["id", "none"] | Omit = omit, record: Literal["record-from-answer"] | Omit = omit, record_channels: Literal["single", "dual"] | Omit = omit, record_custom_file_name: str | Omit = omit, record_format: Literal["wav", "mp3"] | Omit = omit, record_max_length: int | Omit = omit, record_timeout_secs: int | Omit = omit, record_track: Literal["both", "inbound", "outbound"] | Omit = omit, record_trim: Literal["trim-silence"] | Omit = omit, retry_on_timeout: bool | Omit = omit, route_to_mobile: bool | Omit = omit, send_digits_on_answer: str | Omit = omit, send_silence_when_idle: bool | Omit = omit, sip_auth_password: str | Omit = omit, sip_auth_username: str | Omit = omit, sip_headers: Iterable[SipHeaderParam] | Omit = omit, sip_region: Literal["US", "Europe", "Canada", "Australia", "Middle East"] | Omit = omit, sip_transport_protocol: Literal["UDP", "TCP", "TLS"] | Omit = omit, sound_modifications: SoundModificationsParam | Omit = omit, stream_auth_token: str | Omit = omit, stream_bidirectional_codec: StreamBidirectionalCodec | Omit = omit, stream_bidirectional_mode: StreamBidirectionalMode | Omit = omit, stream_bidirectional_sampling_rate: StreamBidirectionalSamplingRate | Omit = omit, stream_bidirectional_target_legs: StreamBidirectionalTargetLegs | Omit = omit, stream_codec: StreamCodec | Omit = omit, stream_establish_before_call_originate: bool | Omit = omit, stream_track: Literal["inbound_track", "outbound_track", "both_tracks"] | Omit = omit, stream_url: str | Omit = omit, supervise_call_control_id: str | Omit = omit, supervisor_role: Literal["barge", "whisper", "monitor"] | Omit = omit, time_limit_secs: int | Omit = omit, timeout_secs: int | Omit = omit, transcription: bool | Omit = omit, transcription_config: TranscriptionStartRequestParam | Omit = omit, webhook_retries_policies: Dict[str, call_dial_params.WebhookRetriesPolicies] | Omit = omit, webhook_url: str | Omit = omit, webhook_url_method: Literal["POST", "GET"] | Omit = omit, webhook_urls: Dict[str, SequenceNotStr[str]] | Omit = omit, webhook_urls_method: Literal["POST", "GET"] | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> CallDialResponse: """Dial a number or SIP URI from a given connection. A successful response will include a `call_leg_id` which can be used to correlate the command with subsequent webhooks. To place the call with an AI assistant from the start, include `assistant.id` and any per-call overrides in the `assistant` object; Telnyx attempts to warm up the assistant before placing the call and starts it automatically when the called party answers. **Expected Webhooks:** - `call.initiated` - `call.answered` or `call.hangup` - `call.conversation.created` when the requested assistant conversation is created, or `call.conversation.start_failed` when it could not be started after the called party answered - `call.hold` and `call.unhold` if the call is held/unheld - `call.machine.detection.ended` if `answering_machine_detection` was requested - `call.machine.greeting.ended` if `answering_machine_detection` was requested to detect the end of machine greeting - `call.machine.premium.detection.ended` if `answering_machine_detection=premium` was requested - `call.machine.premium.greeting.ended` if `answering_machine_detection=premium` was requested and a beep was detected - `call.machine.premium.call_screening.detected` if `answering_machine_detection=premium_ios_call_screening_detection` was requested and an Apple Call Screening tone was detected - `call.deepfake_detection.result` if `deepfake_detection` was enabled - `call.deepfake_detection.error` if `deepfake_detection` was enabled and an error occurred - `streaming.started`, `streaming.stopped` or `streaming.failed` if `stream_url` was set When the `record` parameter is set to `record-from-answer`, the response will include a `recording_id` field. Args: connection_id: The ID of the Call Control App (formerly ID of the connection) to be used when dialing the destination. from_: The `from` number to be used as the caller id presented to the destination (`to` number). The number should be in +E164 format. to: The DID or SIP URI to dial out to. Multiple DID or SIP URIs can be provided using an array of strings. For SIP URI destinations, append `;secure=true` or `;secure=srtp` to enable SRTP media encryption for that endpoint, or `;secure=dtls` to enable DTLS media encryption for that endpoint. If `media_encryption` is set to `SRTP` or `DTLS`, it takes precedence over any per-endpoint `secure` URI parameter. For a single string destination, you may append a comma followed by DTMF digits (e.g. `+18004247767,200`) to play those digits as DTMF once the called party answers — equivalent to setting `send_digits_on_answer` separately. If both are present, the explicit `send_digits_on_answer` parameter takes precedence. This shorthand is not supported when `to` is an array. answering_machine_detection: Enables Answering Machine Detection. Telnyx offers Premium and Standard detections. With Premium detection, when a call is answered, Telnyx runs real-time detection and sends a `call.machine.premium.detection.ended` webhook with one of the following results: `human_residence`, `human_business`, `machine`, `silence` or `fax_detected`. If we detect a beep, we also send a `call.machine.premium.greeting.ended` webhook with the result of `beep_detected`. If we detect a beep before `call.machine.premium.detection.ended` we only send `call.machine.premium.greeting.ended`, and if we detect a beep after `call.machine.premium.detection.ended`, we send both webhooks. With Standard detection, when a call is answered, Telnyx runs real-time detection to determine if it was picked up by a human or a machine and sends an `call.machine.detection.ended` webhook with the analysis result. If `greeting_end` or `detect_words` is used and a `machine` is detected, you will receive another `call.machine.greeting.ended` webhook when the answering machine greeting ends with a beep or silence. If `detect_beep` is used, you will only receive `call.machine.greeting.ended` if a beep is detected. If `answering_machine_detection` is set to `premium_ios_call_screening_detection`, Premium AMD runs with iOS Call Screening support: after an initial `machine` result, Telnyx listens for the iOS call-screening prompt to end or for an Apple Call Screening tone, sends `call.machine.premium.greeting.ended` with `result=prompt_ended` or `call.machine.premium.call_screening.detected` with `result=screening` respectively. When the Apple Call Screening tone is detected, Premium AMD is restarted on the screened call and a `call.machine.premium.detection.ended` webhook with the post-screening classification follows. answering_machine_detection_config: Optional configuration parameters to modify 'answering_machine_detection' performance. Only `total_analysis_time_millis` and `greeting_duration_millis` parameters are applicable when `premium` is selected as answering_machine_detection. `prompt_end_timeout_millis` is additionally applicable when `premium_ios_call_screening_detection` is selected. assistant: AI Assistant configuration and per-call overrides. All fields except `id` are optional. Omitted assistant fields use the stored configuration. Supplied `voice_settings` and `transcription` objects replace their stored objects rather than merging individual settings; include every setting you want to retain. `dynamic_variables` are merged, with request values taking precedence. audio_url: The URL of a file to be played back to the callee when the call is answered. The URL can point to either a WAV or MP3 file. media_name and audio_url cannot be used together in one request. billing_group_id: Use this field to set the Billing Group ID for the call. Must be a valid and existing Billing Group ID. bridge_intent: Indicates the intent to bridge this call with the call specified in link_to. When bridge_intent is true, link_to becomes required and the from number will be overwritten by the from number from the linked call. bridge_on_answer: Whether to automatically bridge answered call to the call specified in link_to. When bridge_on_answer is true, link_to becomes required. client_state: Use this field to add state to every subsequent webhook. It must be a valid Base-64 encoded string. command_id: Use this field to avoid duplicate commands. Telnyx will ignore others Dial commands with the same `command_id`. conference_config: Optional configuration parameters to dial new participant into a conference. conversation_relay_config: Starts a Conversation Relay session automatically when the answered/dialed call is answered. This embedded shape is supported on `answer` and `dial`. It uses public field names (`url`, `dtmf_detection`, `greeting`, `voice`, `language`, etc.) and maps them to the underlying Conversation Relay action. `client_state`, `tts_language`, and `transcription_language` inside this object are ignored; use the parent command's `client_state` and `command_id` fields instead. custom_headers: Custom headers to be added to the SIP INVITE. deepfake_detection: Enables deepfake detection on the call. When enabled, audio from the remote party is streamed to a detection service that analyzes whether the voice is AI-generated. Results are delivered via the `call.deepfake_detection.result` webhook. diversion: The `to` number of an active inbound call, in +E164 format. Telnyx checks whether there is currently an active inbound call where `to` matches this `diversion` value and `from` matches the `from` number supplied for this request. If such a call exists, the `from` number is treated as verified (since it is already on an active inbound call to you) and can be used as the caller id for this outbound call. enable_dialogflow: Enables Dialogflow for the current call. The default value is false. from_display_name: The `from_display_name` string to be used as the caller id name (SIP From Display Name) presented to the destination (`to` number). The string should have a maximum of 128 characters, containing only letters, numbers, spaces, and -\\__~!.+ special characters. If ommited, the display name will be the same as the number in the `from` field. link_to: Use another call's control id for sharing the same call session id media_encryption: Defines whether media should be encrypted on the call. For SIP URI destinations, media encryption can also be requested per endpoint with the `secure` URI parameter: `;secure=true` or `;secure=srtp` enables SRTP, and `;secure=dtls` enables DTLS. This parameter, when set to `SRTP` or `DTLS`, takes precedence over the per-endpoint `secure` value. media_name: The media_name of a file to be played back to the callee when the call is answered. The media_name must point to a file previously uploaded to api.telnyx.com/v2/media by the same user/organization. The file must either be a WAV or MP3 file. park_after_unbridge: If supplied with the value `self`, the current leg will be parked after unbridge. If not set, the default behavior is to hang up the leg. When park_after_unbridge is set, link_to becomes required. preferred_codecs: The list of comma-separated codecs in a preferred order for the forked media to be received. prevent_double_bridge: Prevents bridging and hangs up the call if the target is already bridged. Disabled by default. privacy: Indicates the privacy level to be used for the call. When set to `id`, caller ID information (name and number) will be hidden from the called party. When set to `none` or omitted, caller ID will be shown normally. record: Start recording automatically after an event. Disabled by default. record_channels: Defines which channel should be recorded ('single' or 'dual') when `record` is specified. record_custom_file_name: The custom recording file name to be used instead of the default `call_leg_id`. Telnyx will still add a Unix timestamp suffix. record_format: Defines the format of the recording ('wav' or 'mp3') when `record` is specified. record_max_length: Defines the maximum length for the recording in seconds when `record` is specified. The minimum value is 0. The maximum value is 43200. The default value is 0 (infinite). record_timeout_secs: The number of seconds that Telnyx will wait for the recording to be stopped if silence is detected when `record` is specified. The timer only starts when the speech is detected. Please note that call transcription is used to detect silence and the related charge will be applied. The minimum value is 0. The default value is 0 (infinite). record_track: The audio track to be recorded. Can be either `both`, `inbound` or `outbound`. If only single track is specified (`inbound`, `outbound`), `channels` configuration is ignored and it will be recorded as mono (single channel). record_trim: When set to `trim-silence`, silence will be removed from the beginning and end of the recording. retry_on_timeout: Whether to keep trying the remaining routing paths (e.g. alternate providers/gateways) for the same destination after `timeout_secs` is reached for the current attempt. When set to `false`, reaching `timeout_secs` aborts the entire dial attempt and the `call.hangup` webhook reports a `hangup_cause` of `no_answer` instead of `timeout`. route_to_mobile: When set to true, routes the call directly to the mobile device associated with the destination Telnyx Mobile number, bypassing Inbound Calls Interception configured in the Telnyx Portal under Mobile Numbers → select the number → Voice → Call Interception. Use this when transferring an intercepted call to the mobile device to prevent the call from being intercepted again. Defaults to false. send_digits_on_answer: DTMF digits to send automatically after the called party answers. Useful for reaching an extension behind an IVR (e.g. `"200"` to dial extension 200 once the called party picks up). Allowed characters: `0-9`, `A-D`, `w` (0.5s pause), `W` (1s pause), `*`, `#`. Maximum 64 characters. When omitted, no automatic DTMF is sent. May also be supplied inline by appending `,` to `to` (e.g. `to=+18004247767,200`); if both forms are present, this explicit field takes precedence. send_silence_when_idle: Generate silence RTP packets when no transmission available. sip_auth_password: SIP Authentication password used for SIP challenges. sip_auth_username: SIP Authentication username used for SIP challenges. sip_headers: SIP headers to be added to the SIP INVITE request. Currently only User-to-User header is supported. sip_region: Defines the SIP region to be used for the call. sip_transport_protocol: Defines SIP transport protocol to be used on the call. sound_modifications: Use this field to modify sound effects, for example adjust the pitch. stream_auth_token: An authentication token to be sent as part of the WebSocket connection when using streaming. Maximum length is 4000 characters. stream_bidirectional_codec: Indicates codec for bidirectional streaming RTP payloads. Used only with stream_bidirectional_mode=rtp. Case sensitive. stream_bidirectional_mode: Configures method of bidirectional streaming (mp3, rtp). stream_bidirectional_sampling_rate: Audio sampling rate. stream_bidirectional_target_legs: Specifies which call legs should receive the bidirectional stream audio. stream_codec: Specifies the codec to be used for the streamed audio. When set to 'default' or when transcoding is not possible, the codec from the call will be used. stream_establish_before_call_originate: Establish websocket connection before dialing the destination. This is useful for cases where the websocket connection takes a long time to establish. stream_track: Specifies which track should be streamed. stream_url: The destination WebSocket address where the stream is going to be delivered. supervise_call_control_id: The call leg which will be supervised by the new call. supervisor_role: The role of the supervisor call. 'barge' means that supervisor call hears and is being heard by both ends of the call (caller & callee). 'whisper' means that only supervised_call_control_id hears supervisor but supervisor can hear everything. 'monitor' means that nobody can hear supervisor call, but supervisor can hear everything on the call. time_limit_secs: Sets the maximum duration of a Call Control Leg in seconds. If the time limit is reached, the call will hangup and a `call.hangup` webhook with a `hangup_cause` of `time_limit` will be sent. For example, by setting a time limit of 120 seconds, a Call Leg will be automatically terminated two minutes after being answered. The default time limit is 14400 seconds or 4 hours and this is also the maximum allowed call length. timeout_secs: The number of seconds that Telnyx will wait for the call to be answered by the destination to which it is being called. If the timeout is reached before an answer is received, the call will hangup and a `call.hangup` webhook with a `hangup_cause` of `timeout` will be sent. Minimum value is 5 seconds. Maximum value is 600 seconds. transcription: Enable transcription upon call answer. The default value is false. webhook_retries_policies: A map of event types to retry policies. Each retry policy contains an array of `retries_ms` specifying the delays between retry attempts in milliseconds. Maximum 5 retries, total delay cannot exceed 60 seconds. webhook_url: Use this field to override the URL for which Telnyx will send subsequent webhooks to for this call. webhook_url_method: HTTP request type used for `webhook_url`. webhook_urls: A map of event types to arrays of webhook URLs. When an event of the specified type occurs, the webhook URLs associated with that event type will be called instead of the default webhook URL. Events not mapped here will use the default webhook URL. webhook_urls_method: HTTP request method to invoke `webhook_urls`. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ return await self._post( "/calls", body=await async_maybe_transform( { "connection_id": connection_id, "from_": from_, "to": to, "answering_machine_detection": answering_machine_detection, "answering_machine_detection_config": answering_machine_detection_config, "assistant": assistant, "audio_url": audio_url, "billing_group_id": billing_group_id, "bridge_intent": bridge_intent, "bridge_on_answer": bridge_on_answer, "client_state": client_state, "command_id": command_id, "conference_config": conference_config, "conversation_relay_config": conversation_relay_config, "custom_headers": custom_headers, "deepfake_detection": deepfake_detection, "dialogflow_config": dialogflow_config, "diversion": diversion, "enable_dialogflow": enable_dialogflow, "from_display_name": from_display_name, "link_to": link_to, "media_encryption": media_encryption, "media_name": media_name, "park_after_unbridge": park_after_unbridge, "preferred_codecs": preferred_codecs, "prevent_double_bridge": prevent_double_bridge, "privacy": privacy, "record": record, "record_channels": record_channels, "record_custom_file_name": record_custom_file_name, "record_format": record_format, "record_max_length": record_max_length, "record_timeout_secs": record_timeout_secs, "record_track": record_track, "record_trim": record_trim, "retry_on_timeout": retry_on_timeout, "route_to_mobile": route_to_mobile, "send_digits_on_answer": send_digits_on_answer, "send_silence_when_idle": send_silence_when_idle, "sip_auth_password": sip_auth_password, "sip_auth_username": sip_auth_username, "sip_headers": sip_headers, "sip_region": sip_region, "sip_transport_protocol": sip_transport_protocol, "sound_modifications": sound_modifications, "stream_auth_token": stream_auth_token, "stream_bidirectional_codec": stream_bidirectional_codec, "stream_bidirectional_mode": stream_bidirectional_mode, "stream_bidirectional_sampling_rate": stream_bidirectional_sampling_rate, "stream_bidirectional_target_legs": stream_bidirectional_target_legs, "stream_codec": stream_codec, "stream_establish_before_call_originate": stream_establish_before_call_originate, "stream_track": stream_track, "stream_url": stream_url, "supervise_call_control_id": supervise_call_control_id, "supervisor_role": supervisor_role, "time_limit_secs": time_limit_secs, "timeout_secs": timeout_secs, "transcription": transcription, "transcription_config": transcription_config, "webhook_retries_policies": webhook_retries_policies, "webhook_url": webhook_url, "webhook_url_method": webhook_url_method, "webhook_urls": webhook_urls, "webhook_urls_method": webhook_urls_method, }, call_dial_params.CallDialParams, ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=CallDialResponse, ) async def retrieve_status( self, call_control_id: str, *, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> CallRetrieveStatusResponse: """ Returns the status of a call (data is available 10 minutes after call ended). Args: extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not call_control_id: raise ValueError(f"Expected a non-empty value for `call_control_id` but received {call_control_id!r}") return await self._get( path_template("/calls/{call_control_id}", call_control_id=call_control_id), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=CallRetrieveStatusResponse, ) class CallsResourceWithRawResponse: def __init__(self, calls: CallsResource) -> None: self._calls = calls self.dial = to_raw_response_wrapper( calls.dial, ) self.retrieve_status = to_raw_response_wrapper( calls.retrieve_status, ) @cached_property def actions(self) -> ActionsResourceWithRawResponse: """Call Control command operations""" return ActionsResourceWithRawResponse(self._calls.actions) class AsyncCallsResourceWithRawResponse: def __init__(self, calls: AsyncCallsResource) -> None: self._calls = calls self.dial = async_to_raw_response_wrapper( calls.dial, ) self.retrieve_status = async_to_raw_response_wrapper( calls.retrieve_status, ) @cached_property def actions(self) -> AsyncActionsResourceWithRawResponse: """Call Control command operations""" return AsyncActionsResourceWithRawResponse(self._calls.actions) class CallsResourceWithStreamingResponse: def __init__(self, calls: CallsResource) -> None: self._calls = calls self.dial = to_streamed_response_wrapper( calls.dial, ) self.retrieve_status = to_streamed_response_wrapper( calls.retrieve_status, ) @cached_property def actions(self) -> ActionsResourceWithStreamingResponse: """Call Control command operations""" return ActionsResourceWithStreamingResponse(self._calls.actions) class AsyncCallsResourceWithStreamingResponse: def __init__(self, calls: AsyncCallsResource) -> None: self._calls = calls self.dial = async_to_streamed_response_wrapper( calls.dial, ) self.retrieve_status = async_to_streamed_response_wrapper( calls.retrieve_status, ) @cached_property def actions(self) -> AsyncActionsResourceWithStreamingResponse: """Call Control command operations""" return AsyncActionsResourceWithStreamingResponse(self._calls.actions)