telnyx-voice-gather-python

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
<!-- Auto-generated from Telnyx OpenAPI specs. Do not edit. -->
<!-- Auto-generated from Telnyx OpenAPI specs. Do not edit. -->

Telnyx Voice Gather - Python

Telnyx Voice Gather - Python

Installation

安装

bash
pip install telnyx
bash
pip install telnyx

Setup

初始化配置

python
import os
from telnyx import Telnyx

client = Telnyx(
    api_key=os.environ.get("TELNYX_API_KEY"),  # This is the default and can be omitted
)
All examples below assume
client
is already initialized as shown above.
python
import os
from telnyx import Telnyx

client = Telnyx(
    api_key=os.environ.get("TELNYX_API_KEY"),  # This is the default and can be omitted
)
以下所有示例均假设
client
已按照上述方式完成初始化。

Error Handling

错误处理

All API calls can fail with network errors, rate limits (429), validation errors (422), or authentication errors (401). Always handle errors in production code:
python
import telnyx

try:
    result = client.messages.send(to="+13125550001", from_="+13125550002", text="Hello")
except telnyx.APIConnectionError:
    print("Network error — check connectivity and retry")
except telnyx.RateLimitError:
    # 429: rate limited — wait and retry with exponential backoff
    import time
    time.sleep(1)  # Check Retry-After header for actual delay
except telnyx.APIStatusError as e:
    print(f"API error {e.status_code}: {e.message}")
    if e.status_code == 422:
        print("Validation error — check required fields and formats")
Common error codes:
401
invalid API key,
403
insufficient permissions,
404
resource not found,
422
validation error (check field formats),
429
rate limited (retry with exponential backoff).
所有API调用都可能因网络错误、速率限制(429)、校验错误(422)或身份认证错误(401)而失败。在生产代码中请务必做好错误处理:
python
import telnyx

try:
    result = client.messages.send(to="+13125550001", from_="+13125550002", text="Hello")
except telnyx.APIConnectionError:
    print("Network error — check connectivity and retry")
except telnyx.RateLimitError:
    # 429: 触发速率限制 — 等待后使用指数退避策略重试
    import time
    time.sleep(1)  # 可查看Retry-After请求头获取建议的等待时长

except telnyx.APIStatusError as e:
    print(f"API error {e.status_code}: {e.message}")
    if e.status_code == 422:
        print("校验错误 — 请检查必填字段和格式是否正确")
常见错误码:
401
无效API密钥,
403
权限不足,
404
资源未找到,
422
校验错误(请检查字段格式),
429
触发速率限制(请使用指数退避策略重试)。

Add messages to AI Assistant

向AI助手添加消息

Add messages to the conversation started by an AI assistant on the call.
POST /calls/{call_control_id}/actions/ai_assistant_add_messages
Optional:
client_state
(string),
command_id
(string),
messages
(array[object])
python
response = client.calls.actions.add_ai_assistant_messages(
    call_control_id="550e8400-e29b-41d4-a716-446655440000",
)
print(response.data)
Returns:
result
(string)
为通话中由AI助手开启的会话添加消息。
POST /calls/{call_control_id}/actions/ai_assistant_add_messages
可选参数:
client_state
(字符串),
command_id
(字符串),
messages
(对象数组)
python
response = client.calls.actions.add_ai_assistant_messages(
    call_control_id="550e8400-e29b-41d4-a716-446655440000",
)
print(response.data)
返回值:
result
(字符串)

Start AI Assistant

启动AI助手

Start an AI assistant on the call. Expected Webhooks:
  • call.conversation.ended
  • call.conversation_insights.generated
POST /calls/{call_control_id}/actions/ai_assistant_start
Optional:
assistant
(object),
client_state
(string),
command_id
(string),
greeting
(string),
interruption_settings
(object),
message_history
(array[object]),
participants
(array[object]),
send_message_history_updates
(boolean),
transcription
(object),
voice
(string),
voice_settings
(object)
python
response = client.calls.actions.start_ai_assistant(
    call_control_id="550e8400-e29b-41d4-a716-446655440000",
)
print(response.data)
Returns:
conversation_id
(uuid),
result
(string)
在通话中启动AI助手。预期触发的Webhooks:
  • call.conversation.ended
  • call.conversation_insights.generated
POST /calls/{call_control_id}/actions/ai_assistant_start
可选参数:
assistant
(对象),
client_state
(字符串),
command_id
(字符串),
greeting
(字符串),
interruption_settings
(对象),
message_history
(对象数组),
participants
(对象数组),
send_message_history_updates
(布尔值),
transcription
(对象),
voice
(字符串),
voice_settings
(对象)
python
response = client.calls.actions.start_ai_assistant(
    call_control_id="550e8400-e29b-41d4-a716-446655440000",
)
print(response.data)
返回值:
conversation_id
(uuid),
result
(字符串)

Stop AI Assistant

停止AI助手

Stop an AI assistant on the call.
POST /calls/{call_control_id}/actions/ai_assistant_stop
Optional:
client_state
(string),
command_id
(string)
python
response = client.calls.actions.stop_ai_assistant(
    call_control_id="550e8400-e29b-41d4-a716-446655440000",
)
print(response.data)
Returns:
result
(string)
停止通话中的AI助手。
POST /calls/{call_control_id}/actions/ai_assistant_stop
可选参数:
client_state
(字符串),
command_id
(字符串)
python
response = client.calls.actions.stop_ai_assistant(
    call_control_id="550e8400-e29b-41d4-a716-446655440000",
)
print(response.data)
返回值:
result
(字符串)

Gather

Gather

Gather DTMF signals to build interactive menus. You can pass a list of valid digits. The
Answer
command must be issued before the
gather
command.
POST /calls/{call_control_id}/actions/gather
Optional:
client_state
(string),
command_id
(string),
gather_id
(string),
initial_timeout_millis
(int32),
inter_digit_timeout_millis
(int32),
maximum_digits
(int32),
minimum_digits
(int32),
terminating_digit
(string),
timeout_millis
(int32),
valid_digits
(string)
python
response = client.calls.actions.gather(
    call_control_id="550e8400-e29b-41d4-a716-446655440000",
    minimum_digits=1,
    maximum_digits=4,
)
print(response.data)
Returns:
result
(string)
采集DTMF信号以构建交互式菜单。你可以传入有效数字列表。
gather
命令执行前必须先调用
Answer
命令。
POST /calls/{call_control_id}/actions/gather
可选参数:
client_state
(字符串),
command_id
(字符串),
gather_id
(字符串),
initial_timeout_millis
(int32),
inter_digit_timeout_millis
(int32),
maximum_digits
(int32),
minimum_digits
(int32),
terminating_digit
(字符串),
timeout_millis
(int32),
valid_digits
(字符串)
python
response = client.calls.actions.gather(
    call_control_id="550e8400-e29b-41d4-a716-446655440000",
    minimum_digits=1,
    maximum_digits=4,
)
print(response.data)
返回值:
result
(字符串)

Gather stop

停止Gather

Stop current gather. Expected Webhooks:
  • call.gather.ended
POST /calls/{call_control_id}/actions/gather_stop
Optional:
client_state
(string),
command_id
(string)
python
response = client.calls.actions.stop_gather(
    call_control_id="550e8400-e29b-41d4-a716-446655440000",
)
print(response.data)
Returns:
result
(string)
终止当前的gather操作。预期触发的Webhooks:
  • call.gather.ended
POST /calls/{call_control_id}/actions/gather_stop
可选参数:
client_state
(字符串),
command_id
(字符串)
python
response = client.calls.actions.stop_gather(
    call_control_id="550e8400-e29b-41d4-a716-446655440000",
)
print(response.data)
返回值:
result
(字符串)

Gather using AI

使用AI进行Gather

Gather parameters defined in the request payload using a voice assistant. You can pass parameters described as a JSON Schema object and the voice assistant will attempt to gather these informations.
POST /calls/{call_control_id}/actions/gather_using_ai
— Required:
parameters
Optional:
assistant
(object),
client_state
(string),
command_id
(string),
gather_ended_speech
(string),
greeting
(string),
interruption_settings
(object),
language
(object),
message_history
(array[object]),
send_message_history_updates
(boolean),
send_partial_results
(boolean),
transcription
(object),
user_response_timeout_ms
(integer),
voice
(string),
voice_settings
(object)
python
response = client.calls.actions.gather_using_ai(
    call_control_id="550e8400-e29b-41d4-a716-446655440000",
    parameters={
        "properties": "bar",
        "required": "bar",
        "type": "bar",
    },
)
print(response.data)
Returns:
conversation_id
(uuid),
result
(string)
通过语音助手采集请求负载中定义的参数。你可以传入以JSON Schema对象描述的参数,语音助手会尝试采集这些信息。
POST /calls/{call_control_id}/actions/gather_using_ai
— 必填参数:
parameters
可选参数:
assistant
(对象),
client_state
(字符串),
command_id
(字符串),
gather_ended_speech
(字符串),
greeting
(字符串),
interruption_settings
(对象),
language
(对象),
message_history
(对象数组),
send_message_history_updates
(布尔值),
send_partial_results
(布尔值),
transcription
(对象),
user_response_timeout_ms
(整数),
voice
(字符串),
voice_settings
(对象)
python
response = client.calls.actions.gather_using_ai(
    call_control_id="550e8400-e29b-41d4-a716-446655440000",
    parameters={
        "properties": "bar",
        "required": "bar",
        "type": "bar",
    },
)
print(response.data)
返回值:
conversation_id
(uuid),
result
(字符串)

Gather using audio

使用音频进行Gather

Play an audio file on the call until the required DTMF signals are gathered to build interactive menus. You can pass a list of valid digits along with an 'invalid_audio_url', which will be played back at the beginning of each prompt. Playback will be interrupted when a DTMF signal is received.
POST /calls/{call_control_id}/actions/gather_using_audio
Optional:
audio_url
(string),
client_state
(string),
command_id
(string),
inter_digit_timeout_millis
(int32),
invalid_audio_url
(string),
invalid_media_name
(string),
maximum_digits
(int32),
maximum_tries
(int32),
media_name
(string),
minimum_digits
(int32),
terminating_digit
(string),
timeout_millis
(int32),
valid_digits
(string)
python
response = client.calls.actions.gather_using_audio(
    call_control_id="550e8400-e29b-41d4-a716-446655440000",
)
print(response.data)
Returns:
result
(string)
在通话中播放音频文件,直到采集到所需的DTMF信号以构建交互式菜单。你可以传入有效数字列表以及
invalid_audio_url
,每次提示开始时都会播放该音频。收到DTMF信号时会中断播放。
POST /calls/{call_control_id}/actions/gather_using_audio
可选参数:
audio_url
(字符串),
client_state
(字符串),
command_id
(字符串),
inter_digit_timeout_millis
(int32),
invalid_audio_url
(字符串),
invalid_media_name
(字符串),
maximum_digits
(int32),
maximum_tries
(int32),
media_name
(字符串),
minimum_digits
(int32),
terminating_digit
(字符串),
timeout_millis
(int32),
valid_digits
(字符串)
python
response = client.calls.actions.gather_using_audio(
    call_control_id="550e8400-e29b-41d4-a716-446655440000",
)
print(response.data)
返回值:
result
(字符串)

Gather using speak

使用语音合成进行Gather

Convert text to speech and play it on the call until the required DTMF signals are gathered to build interactive menus. You can pass a list of valid digits along with an 'invalid_payload', which will be played back at the beginning of each prompt. Speech will be interrupted when a DTMF signal is received.
POST /calls/{call_control_id}/actions/gather_using_speak
— Required:
voice
,
payload
Optional:
client_state
(string),
command_id
(string),
inter_digit_timeout_millis
(int32),
invalid_payload
(string),
language
(enum: arb, cmn-CN, cy-GB, da-DK, de-DE, en-AU, en-GB, en-GB-WLS, en-IN, en-US, es-ES, es-MX, es-US, fr-CA, fr-FR, hi-IN, is-IS, it-IT, ja-JP, ko-KR, nb-NO, nl-NL, pl-PL, pt-BR, pt-PT, ro-RO, ru-RU, sv-SE, tr-TR),
maximum_digits
(int32),
maximum_tries
(int32),
minimum_digits
(int32),
payload_type
(enum: text, ssml),
service_level
(enum: basic, premium),
terminating_digit
(string),
timeout_millis
(int32),
valid_digits
(string),
voice_settings
(object)
python
response = client.calls.actions.gather_using_speak(
    call_control_id="550e8400-e29b-41d4-a716-446655440000",
    payload="say this on call",
    voice="male",
)
print(response.data)
Returns:
result
(string)

将文本转换为语音并在通话中播放,直到采集到所需的DTMF信号以构建交互式菜单。你可以传入有效数字列表以及
invalid_payload
,每次提示开始时都会播放对应内容。收到DTMF信号时会中断语音播放。
POST /calls/{call_control_id}/actions/gather_using_speak
— 必填参数:
voice
,
payload
可选参数:
client_state
(字符串),
command_id
(字符串),
inter_digit_timeout_millis
(int32),
invalid_payload
(字符串),
language
(枚举: arb, cmn-CN, cy-GB, da-DK, de-DE, en-AU, en-GB, en-GB-WLS, en-IN, en-US, es-ES, es-MX, es-US, fr-CA, fr-FR, hi-IN, is-IS, it-IT, ja-JP, ko-KR, nb-NO, nl-NL, pl-PL, pt-BR, pt-PT, ro-RO, ru-RU, sv-SE, tr-TR),
maximum_digits
(int32),
maximum_tries
(int32),
minimum_digits
(int32),
payload_type
(枚举: text, ssml),
service_level
(枚举: basic, premium),
terminating_digit
(字符串),
timeout_millis
(int32),
valid_digits
(字符串),
voice_settings
(对象)
python
response = client.calls.actions.gather_using_speak(
    call_control_id="550e8400-e29b-41d4-a716-446655440000",
    payload="say this on call",
    voice="male",
)
print(response.data)
返回值:
result
(字符串)

Webhooks

Webhooks

Webhook Verification

Webhook验证

Telnyx signs webhooks with Ed25519. Each request includes
telnyx-signature-ed25519
and
telnyx-timestamp
headers. Always verify signatures in production:
python
undefined
Telnyx使用Ed25519对Webhooks进行签名。每个请求都包含
telnyx-signature-ed25519
telnyx-timestamp
请求头。生产环境中请务必验证签名:
python
undefined

In your webhook handler (e.g., Flask — use raw body, not parsed JSON):

在你的Webhook处理逻辑中(例如Flask — 请使用原始请求体,不要使用解析后的JSON):

@app.route("/webhooks", methods=["POST"]) def handle_webhook(): payload = request.get_data(as_text=True) # raw body as string headers = dict(request.headers) try: event = client.webhooks.unwrap(payload, headers=headers) except Exception as e: print(f"Webhook verification failed: {e}") return "Invalid signature", 400 # Signature valid — event is the parsed webhook payload print(f"Received event: {event.data.event_type}") return "OK", 200

The following webhook events are sent to your configured webhook URL.
All webhooks include `telnyx-timestamp` and `telnyx-signature-ed25519` headers for Ed25519 signature verification. Use `client.webhooks.unwrap()` to verify.

| Event | Description |
|-------|-------------|
| `CallAIGatherEnded` | Call AI Gather Ended |
| `CallAIGatherMessageHistoryUpdated` | Call AI Gather Message History Updated |
| `CallAIGatherPartialResults` | Call AI Gather Partial Results |
| `callGatherEnded` | Call Gather Ended |
@app.route("/webhooks", methods=["POST"]) def handle_webhook(): payload = request.get_data(as_text=True) # 字符串格式的原始请求体 headers = dict(request.headers) try: event = client.webhooks.unwrap(payload, headers=headers) except Exception as e: print(f"Webhook验证失败: {e}") return "Invalid signature", 400 # 签名验证通过 — event为解析后的Webhook负载 print(f"收到事件: {event.data.event_type}") return "OK", 200

以下Webhook事件会发送到你配置的Webhook URL。所有Webhooks都包含`telnyx-timestamp`和`telnyx-signature-ed25519`头用于Ed25519签名验证,可使用`client.webhooks.unwrap()`方法完成验证。

| 事件 | 描述 |
|-------|-------------|
| `CallAIGatherEnded` | 通话AI采集结束 |
| `CallAIGatherMessageHistoryUpdated` | 通话AI采集消息历史更新 |
| `CallAIGatherPartialResults` | 通话AI采集返回部分结果 |
| `callGatherEnded` | 通话采集结束 |

Webhook payload fields

Webhook负载字段

CallAIGatherEnded
FieldTypeDescription
data.record_type
enum: eventIdentifies the type of the resource.
data.event_type
enum: call.ai_gather.endedThe type of event being delivered.
data.id
uuidIdentifies the type of resource.
data.occurred_at
date-timeISO 8601 datetime of when the event occurred.
data.payload.call_control_id
stringCall ID used to issue commands via Call Control API.
data.payload.connection_id
stringTelnyx connection ID used in the call.
data.payload.call_leg_id
stringID that is unique to the call and can be used to correlate webhook events.
data.payload.call_session_id
stringID that is unique to the call session and can be used to correlate webhook events.
data.payload.client_state
stringState received from a command.
data.payload.from
stringNumber or SIP URI placing the call.
data.payload.to
stringDestination number or SIP URI of the call.
data.payload.message_history
array[object]The history of the messages exchanged during the AI gather
data.payload.result
objectThe result of the AI gather, its type depends of the
parameters
provided in the command
data.payload.status
enum: valid, invalidReflects how command ended.
CallAIGatherMessageHistoryUpdated
FieldTypeDescription
data.record_type
enum: eventIdentifies the type of the resource.
data.event_type
enum: call.ai_gather.message_history_updatedThe type of event being delivered.
data.id
uuidIdentifies the type of resource.
data.occurred_at
date-timeISO 8601 datetime of when the event occurred.
data.payload.call_control_id
stringCall ID used to issue commands via Call Control API.
data.payload.connection_id
stringTelnyx connection ID used in the call.
data.payload.call_leg_id
stringID that is unique to the call and can be used to correlate webhook events.
data.payload.call_session_id
stringID that is unique to the call session and can be used to correlate webhook events.
data.payload.client_state
stringState received from a command.
data.payload.from
stringNumber or SIP URI placing the call.
data.payload.to
stringDestination number or SIP URI of the call.
data.payload.message_history
array[object]The history of the messages exchanged during the AI gather
CallAIGatherPartialResults
FieldTypeDescription
data.record_type
enum: eventIdentifies the type of the resource.
data.event_type
enum: call.ai_gather.partial_resultsThe type of event being delivered.
data.id
uuidIdentifies the type of resource.
data.occurred_at
date-timeISO 8601 datetime of when the event occurred.
data.payload.call_control_id
stringCall ID used to issue commands via Call Control API.
data.payload.connection_id
stringTelnyx connection ID used in the call.
data.payload.call_leg_id
stringID that is unique to the call and can be used to correlate webhook events.
data.payload.call_session_id
stringID that is unique to the call session and can be used to correlate webhook events.
data.payload.client_state
stringState received from a command.
data.payload.from
stringNumber or SIP URI placing the call.
data.payload.to
stringDestination number or SIP URI of the call.
data.payload.message_history
array[object]The history of the messages exchanged during the AI gather
data.payload.partial_results
objectThe partial result of the AI gather, its type depends of the
parameters
provided in the command
callGatherEnded
FieldTypeDescription
data.record_type
enum: eventIdentifies the type of the resource.
data.event_type
enum: call.gather.endedThe type of event being delivered.
data.id
uuidIdentifies the type of resource.
data.occurred_at
date-timeISO 8601 datetime of when the event occurred.
data.payload.call_control_id
stringCall ID used to issue commands via Call Control API.
data.payload.connection_id
stringCall Control App ID (formerly Telnyx connection ID) used in the call.
data.payload.call_leg_id
stringID that is unique to the call and can be used to correlate webhook events.
data.payload.call_session_id
stringID that is unique to the call session and can be used to correlate webhook events.
data.payload.client_state
stringState received from a command.
data.payload.from
stringNumber or SIP URI placing the call.
data.payload.to
stringDestination number or SIP URI of the call.
data.payload.digits
stringThe received DTMF digit or symbol.
data.payload.status
enum: valid, invalid, call_hangup, cancelled, cancelled_amd, timeoutReflects how command ended.
CallAIGatherEnded
字段类型描述
data.record_type
枚举: event标识资源类型
data.event_type
枚举: call.ai_gather.ended交付的事件类型
data.id
uuid资源标识ID
data.occurred_at
date-time事件发生的ISO 8601格式时间戳
data.payload.call_control_id
字符串用于通过呼叫控制API下发指令的通话ID
data.payload.connection_id
字符串本次通话使用的Telnyx连接ID
data.payload.call_leg_id
字符串通话唯一ID,可用于关联Webhook事件
data.payload.call_session_id
字符串通话会话唯一ID,可用于关联Webhook事件
data.payload.client_state
字符串从指令中获取的状态信息
data.payload.from
字符串主叫号码或SIP URI
data.payload.to
字符串被叫号码或SIP URI
data.payload.message_history
对象数组AI采集过程中 exchanged的消息历史
data.payload.result
对象AI采集的结果,类型取决于指令中传入的
parameters
data.payload.status
枚举: valid, invalid指令结束的状态
CallAIGatherMessageHistoryUpdated
字段类型描述
data.record_type
枚举: event标识资源类型
data.event_type
枚举: call.ai_gather.message_history_updated交付的事件类型
data.id
uuid资源标识ID
data.occurred_at
date-time事件发生的ISO 8601格式时间戳
data.payload.call_control_id
字符串用于通过呼叫控制API下发指令的通话ID
data.payload.connection_id
字符串本次通话使用的Telnyx连接ID
data.payload.call_leg_id
字符串通话唯一ID,可用于关联Webhook事件
data.payload.call_session_id
字符串通话会话唯一ID,可用于关联Webhook事件
data.payload.client_state
字符串从指令中获取的状态信息
data.payload.from
字符串主叫号码或SIP URI
data.payload.to
字符串被叫号码或SIP URI
data.payload.message_history
对象数组AI采集过程中 exchanged的消息历史
CallAIGatherPartialResults
字段类型描述
data.record_type
枚举: event标识资源类型
data.event_type
枚举: call.ai_gather.partial_results交付的事件类型
data.id
uuid资源标识ID
data.occurred_at
date-time事件发生的ISO 8601格式时间戳
data.payload.call_control_id
字符串用于通过呼叫控制API下发指令的通话ID
data.payload.connection_id
字符串本次通话使用的Telnyx连接ID
data.payload.call_leg_id
字符串通话唯一ID,可用于关联Webhook事件
data.payload.call_session_id
字符串通话会话唯一ID,可用于关联Webhook事件
data.payload.client_state
字符串从指令中获取的状态信息
data.payload.from
字符串主叫号码或SIP URI
data.payload.to
字符串被叫号码或SIP URI
data.payload.message_history
对象数组AI采集过程中 exchanged的消息历史
data.payload.partial_results
对象AI采集的部分结果,类型取决于指令中传入的
parameters
callGatherEnded
字段类型描述
data.record_type
枚举: event标识资源类型
data.event_type
枚举: call.gather.ended交付的事件类型
data.id
uuid资源标识ID
data.occurred_at
date-time事件发生的ISO 8601格式时间戳
data.payload.call_control_id
字符串用于通过呼叫控制API下发指令的通话ID
data.payload.connection_id
字符串本次通话使用的呼叫控制应用ID(原Telnyx连接ID)
data.payload.call_leg_id
字符串通话唯一ID,可用于关联Webhook事件
data.payload.call_session_id
字符串通话会话唯一ID,可用于关联Webhook事件
data.payload.client_state
字符串从指令中获取的状态信息
data.payload.from
字符串主叫号码或SIP URI
data.payload.to
字符串被叫号码或SIP URI
data.payload.digits
字符串收到的DTMF数字或符号
data.payload.status
枚举: valid, invalid, call_hangup, cancelled, cancelled_amd, timeout指令结束的状态