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 telnyxbash
pip install telnyxSetup
初始化配置
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 is already initialized as shown above.
clientpython
import os
from telnyx import Telnyx
client = Telnyx(
api_key=os.environ.get("TELNYX_API_KEY"), # This is the default and can be omitted
)以下所有示例均假设已按照上述方式完成初始化。
clientError 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: invalid API key, insufficient permissions,
resource not found, validation error (check field formats),
rate limited (retry with exponential backoff).
401403404422429所有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("校验错误 — 请检查必填字段和格式是否正确")常见错误码: 无效API密钥, 权限不足, 资源未找到, 校验错误(请检查字段格式), 触发速率限制(请使用指数退避策略重试)。
401403404422429Add 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_messagesOptional: (string), (string), (array[object])
client_statecommand_idmessagespython
response = client.calls.actions.add_ai_assistant_messages(
call_control_id="550e8400-e29b-41d4-a716-446655440000",
)
print(response.data)Returns: (string)
result为通话中由AI助手开启的会话添加消息。
POST /calls/{call_control_id}/actions/ai_assistant_add_messages可选参数: (字符串), (字符串), (对象数组)
client_statecommand_idmessagespython
response = client.calls.actions.add_ai_assistant_messages(
call_control_id="550e8400-e29b-41d4-a716-446655440000",
)
print(response.data)返回值: (字符串)
resultStart AI Assistant
启动AI助手
Start an AI assistant on the call. Expected Webhooks:
call.conversation.endedcall.conversation_insights.generated
POST /calls/{call_control_id}/actions/ai_assistant_startOptional: (object), (string), (string), (string), (object), (array[object]), (array[object]), (boolean), (object), (string), (object)
assistantclient_statecommand_idgreetinginterruption_settingsmessage_historyparticipantssend_message_history_updatestranscriptionvoicevoice_settingspython
response = client.calls.actions.start_ai_assistant(
call_control_id="550e8400-e29b-41d4-a716-446655440000",
)
print(response.data)Returns: (uuid), (string)
conversation_idresult在通话中启动AI助手。预期触发的Webhooks:
call.conversation.endedcall.conversation_insights.generated
POST /calls/{call_control_id}/actions/ai_assistant_start可选参数: (对象), (字符串), (字符串), (字符串), (对象), (对象数组), (对象数组), (布尔值), (对象), (字符串), (对象)
assistantclient_statecommand_idgreetinginterruption_settingsmessage_historyparticipantssend_message_history_updatestranscriptionvoicevoice_settingspython
response = client.calls.actions.start_ai_assistant(
call_control_id="550e8400-e29b-41d4-a716-446655440000",
)
print(response.data)返回值: (uuid), (字符串)
conversation_idresultStop AI Assistant
停止AI助手
Stop an AI assistant on the call.
POST /calls/{call_control_id}/actions/ai_assistant_stopOptional: (string), (string)
client_statecommand_idpython
response = client.calls.actions.stop_ai_assistant(
call_control_id="550e8400-e29b-41d4-a716-446655440000",
)
print(response.data)Returns: (string)
result停止通话中的AI助手。
POST /calls/{call_control_id}/actions/ai_assistant_stop可选参数: (字符串), (字符串)
client_statecommand_idpython
response = client.calls.actions.stop_ai_assistant(
call_control_id="550e8400-e29b-41d4-a716-446655440000",
)
print(response.data)返回值: (字符串)
resultGather
Gather
Gather DTMF signals to build interactive menus. You can pass a list of valid digits. The command must be issued before the command.
AnswergatherPOST /calls/{call_control_id}/actions/gatherOptional: (string), (string), (string), (int32), (int32), (int32), (int32), (string), (int32), (string)
client_statecommand_idgather_idinitial_timeout_millisinter_digit_timeout_millismaximum_digitsminimum_digitsterminating_digittimeout_millisvalid_digitspython
response = client.calls.actions.gather(
call_control_id="550e8400-e29b-41d4-a716-446655440000",
minimum_digits=1,
maximum_digits=4,
)
print(response.data)Returns: (string)
result采集DTMF信号以构建交互式菜单。你可以传入有效数字列表。命令执行前必须先调用命令。
gatherAnswerPOST /calls/{call_control_id}/actions/gather可选参数: (字符串), (字符串), (字符串), (int32), (int32), (int32), (int32), (字符串), (int32), (字符串)
client_statecommand_idgather_idinitial_timeout_millisinter_digit_timeout_millismaximum_digitsminimum_digitsterminating_digittimeout_millisvalid_digitspython
response = client.calls.actions.gather(
call_control_id="550e8400-e29b-41d4-a716-446655440000",
minimum_digits=1,
maximum_digits=4,
)
print(response.data)返回值: (字符串)
resultGather stop
停止Gather
Stop current gather. Expected Webhooks:
call.gather.ended
POST /calls/{call_control_id}/actions/gather_stopOptional: (string), (string)
client_statecommand_idpython
response = client.calls.actions.stop_gather(
call_control_id="550e8400-e29b-41d4-a716-446655440000",
)
print(response.data)Returns: (string)
result终止当前的gather操作。预期触发的Webhooks:
call.gather.ended
POST /calls/{call_control_id}/actions/gather_stop可选参数: (字符串), (字符串)
client_statecommand_idpython
response = client.calls.actions.stop_gather(
call_control_id="550e8400-e29b-41d4-a716-446655440000",
)
print(response.data)返回值: (字符串)
resultGather 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_aiparametersOptional: (object), (string), (string), (string), (string), (object), (object), (array[object]), (boolean), (boolean), (object), (integer), (string), (object)
assistantclient_statecommand_idgather_ended_speechgreetinginterruption_settingslanguagemessage_historysend_message_history_updatessend_partial_resultstranscriptionuser_response_timeout_msvoicevoice_settingspython
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: (uuid), (string)
conversation_idresult通过语音助手采集请求负载中定义的参数。你可以传入以JSON Schema对象描述的参数,语音助手会尝试采集这些信息。
POST /calls/{call_control_id}/actions/gather_using_aiparameters可选参数: (对象), (字符串), (字符串), (字符串), (字符串), (对象), (对象), (对象数组), (布尔值), (布尔值), (对象), (整数), (字符串), (对象)
assistantclient_statecommand_idgather_ended_speechgreetinginterruption_settingslanguagemessage_historysend_message_history_updatessend_partial_resultstranscriptionuser_response_timeout_msvoicevoice_settingspython
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)返回值: (uuid), (字符串)
conversation_idresultGather 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_audioOptional: (string), (string), (string), (int32), (string), (string), (int32), (int32), (string), (int32), (string), (int32), (string)
audio_urlclient_statecommand_idinter_digit_timeout_millisinvalid_audio_urlinvalid_media_namemaximum_digitsmaximum_triesmedia_nameminimum_digitsterminating_digittimeout_millisvalid_digitspython
response = client.calls.actions.gather_using_audio(
call_control_id="550e8400-e29b-41d4-a716-446655440000",
)
print(response.data)Returns: (string)
result在通话中播放音频文件,直到采集到所需的DTMF信号以构建交互式菜单。你可以传入有效数字列表以及,每次提示开始时都会播放该音频。收到DTMF信号时会中断播放。
invalid_audio_urlPOST /calls/{call_control_id}/actions/gather_using_audio可选参数: (字符串), (字符串), (字符串), (int32), (字符串), (字符串), (int32), (int32), (字符串), (int32), (字符串), (int32), (字符串)
audio_urlclient_statecommand_idinter_digit_timeout_millisinvalid_audio_urlinvalid_media_namemaximum_digitsmaximum_triesmedia_nameminimum_digitsterminating_digittimeout_millisvalid_digitspython
response = client.calls.actions.gather_using_audio(
call_control_id="550e8400-e29b-41d4-a716-446655440000",
)
print(response.data)返回值: (字符串)
resultGather 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_speakvoicepayloadOptional: (string), (string), (int32), (string), (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), (int32), (int32), (int32), (enum: text, ssml), (enum: basic, premium), (string), (int32), (string), (object)
client_statecommand_idinter_digit_timeout_millisinvalid_payloadlanguagemaximum_digitsmaximum_triesminimum_digitspayload_typeservice_levelterminating_digittimeout_millisvalid_digitsvoice_settingspython
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: (string)
result将文本转换为语音并在通话中播放,直到采集到所需的DTMF信号以构建交互式菜单。你可以传入有效数字列表以及,每次提示开始时都会播放对应内容。收到DTMF信号时会中断语音播放。
invalid_payloadPOST /calls/{call_control_id}/actions/gather_using_speakvoicepayload可选参数: (字符串), (字符串), (int32), (字符串), (枚举: 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), (int32), (int32), (int32), (枚举: text, ssml), (枚举: basic, premium), (字符串), (int32), (字符串), (对象)
client_statecommand_idinter_digit_timeout_millisinvalid_payloadlanguagemaximum_digitsmaximum_triesminimum_digitspayload_typeservice_levelterminating_digittimeout_millisvalid_digitsvoice_settingspython
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)返回值: (字符串)
resultWebhooks
Webhooks
Webhook Verification
Webhook验证
Telnyx signs webhooks with Ed25519. Each request includes
and headers. Always verify signatures in production:
telnyx-signature-ed25519telnyx-timestamppython
undefinedTelnyx使用Ed25519对Webhooks进行签名。每个请求都包含和请求头。生产环境中请务必验证签名:
telnyx-signature-ed25519telnyx-timestamppython
undefinedIn 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| Field | Type | Description |
|---|---|---|
| enum: event | Identifies the type of the resource. |
| enum: call.ai_gather.ended | The type of event being delivered. |
| uuid | Identifies the type of resource. |
| date-time | ISO 8601 datetime of when the event occurred. |
| string | Call ID used to issue commands via Call Control API. |
| string | Telnyx connection ID used in the call. |
| string | ID that is unique to the call and can be used to correlate webhook events. |
| string | ID that is unique to the call session and can be used to correlate webhook events. |
| string | State received from a command. |
| string | Number or SIP URI placing the call. |
| string | Destination number or SIP URI of the call. |
| array[object] | The history of the messages exchanged during the AI gather |
| object | The result of the AI gather, its type depends of the |
| enum: valid, invalid | Reflects how command ended. |
CallAIGatherMessageHistoryUpdated| Field | Type | Description |
|---|---|---|
| enum: event | Identifies the type of the resource. |
| enum: call.ai_gather.message_history_updated | The type of event being delivered. |
| uuid | Identifies the type of resource. |
| date-time | ISO 8601 datetime of when the event occurred. |
| string | Call ID used to issue commands via Call Control API. |
| string | Telnyx connection ID used in the call. |
| string | ID that is unique to the call and can be used to correlate webhook events. |
| string | ID that is unique to the call session and can be used to correlate webhook events. |
| string | State received from a command. |
| string | Number or SIP URI placing the call. |
| string | Destination number or SIP URI of the call. |
| array[object] | The history of the messages exchanged during the AI gather |
CallAIGatherPartialResults| Field | Type | Description |
|---|---|---|
| enum: event | Identifies the type of the resource. |
| enum: call.ai_gather.partial_results | The type of event being delivered. |
| uuid | Identifies the type of resource. |
| date-time | ISO 8601 datetime of when the event occurred. |
| string | Call ID used to issue commands via Call Control API. |
| string | Telnyx connection ID used in the call. |
| string | ID that is unique to the call and can be used to correlate webhook events. |
| string | ID that is unique to the call session and can be used to correlate webhook events. |
| string | State received from a command. |
| string | Number or SIP URI placing the call. |
| string | Destination number or SIP URI of the call. |
| array[object] | The history of the messages exchanged during the AI gather |
| object | The partial result of the AI gather, its type depends of the |
callGatherEnded| Field | Type | Description |
|---|---|---|
| enum: event | Identifies the type of the resource. |
| enum: call.gather.ended | The type of event being delivered. |
| uuid | Identifies the type of resource. |
| date-time | ISO 8601 datetime of when the event occurred. |
| string | Call ID used to issue commands via Call Control API. |
| string | Call Control App ID (formerly Telnyx connection ID) used in the call. |
| string | ID that is unique to the call and can be used to correlate webhook events. |
| string | ID that is unique to the call session and can be used to correlate webhook events. |
| string | State received from a command. |
| string | Number or SIP URI placing the call. |
| string | Destination number or SIP URI of the call. |
| string | The received DTMF digit or symbol. |
| enum: valid, invalid, call_hangup, cancelled, cancelled_amd, timeout | Reflects how command ended. |
CallAIGatherEnded| 字段 | 类型 | 描述 |
|---|---|---|
| 枚举: event | 标识资源类型 |
| 枚举: call.ai_gather.ended | 交付的事件类型 |
| uuid | 资源标识ID |
| date-time | 事件发生的ISO 8601格式时间戳 |
| 字符串 | 用于通过呼叫控制API下发指令的通话ID |
| 字符串 | 本次通话使用的Telnyx连接ID |
| 字符串 | 通话唯一ID,可用于关联Webhook事件 |
| 字符串 | 通话会话唯一ID,可用于关联Webhook事件 |
| 字符串 | 从指令中获取的状态信息 |
| 字符串 | 主叫号码或SIP URI |
| 字符串 | 被叫号码或SIP URI |
| 对象数组 | AI采集过程中 exchanged的消息历史 |
| 对象 | AI采集的结果,类型取决于指令中传入的 |
| 枚举: valid, invalid | 指令结束的状态 |
CallAIGatherMessageHistoryUpdated| 字段 | 类型 | 描述 |
|---|---|---|
| 枚举: event | 标识资源类型 |
| 枚举: call.ai_gather.message_history_updated | 交付的事件类型 |
| uuid | 资源标识ID |
| date-time | 事件发生的ISO 8601格式时间戳 |
| 字符串 | 用于通过呼叫控制API下发指令的通话ID |
| 字符串 | 本次通话使用的Telnyx连接ID |
| 字符串 | 通话唯一ID,可用于关联Webhook事件 |
| 字符串 | 通话会话唯一ID,可用于关联Webhook事件 |
| 字符串 | 从指令中获取的状态信息 |
| 字符串 | 主叫号码或SIP URI |
| 字符串 | 被叫号码或SIP URI |
| 对象数组 | AI采集过程中 exchanged的消息历史 |
CallAIGatherPartialResults| 字段 | 类型 | 描述 |
|---|---|---|
| 枚举: event | 标识资源类型 |
| 枚举: call.ai_gather.partial_results | 交付的事件类型 |
| uuid | 资源标识ID |
| date-time | 事件发生的ISO 8601格式时间戳 |
| 字符串 | 用于通过呼叫控制API下发指令的通话ID |
| 字符串 | 本次通话使用的Telnyx连接ID |
| 字符串 | 通话唯一ID,可用于关联Webhook事件 |
| 字符串 | 通话会话唯一ID,可用于关联Webhook事件 |
| 字符串 | 从指令中获取的状态信息 |
| 字符串 | 主叫号码或SIP URI |
| 字符串 | 被叫号码或SIP URI |
| 对象数组 | AI采集过程中 exchanged的消息历史 |
| 对象 | AI采集的部分结果,类型取决于指令中传入的 |
callGatherEnded| 字段 | 类型 | 描述 |
|---|---|---|
| 枚举: event | 标识资源类型 |
| 枚举: call.gather.ended | 交付的事件类型 |
| uuid | 资源标识ID |
| date-time | 事件发生的ISO 8601格式时间戳 |
| 字符串 | 用于通过呼叫控制API下发指令的通话ID |
| 字符串 | 本次通话使用的呼叫控制应用ID(原Telnyx连接ID) |
| 字符串 | 通话唯一ID,可用于关联Webhook事件 |
| 字符串 | 通话会话唯一ID,可用于关联Webhook事件 |
| 字符串 | 从指令中获取的状态信息 |
| 字符串 | 主叫号码或SIP URI |
| 字符串 | 被叫号码或SIP URI |
| 字符串 | 收到的DTMF数字或符号 |
| 枚举: valid, invalid, call_hangup, cancelled, cancelled_amd, timeout | 指令结束的状态 |