telnyx-voice-gather-javascript
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinese<!-- Auto-generated from Telnyx OpenAPI specs. Do not edit. -->
<!-- 由Telnyx OpenAPI规范自动生成,请勿编辑 -->
Telnyx Voice Gather - JavaScript
Telnyx 语音采集 - JavaScript
Installation
安装
bash
npm install telnyxbash
npm install telnyxSetup
配置
javascript
import Telnyx from 'telnyx';
const client = new Telnyx({
apiKey: process.env['TELNYX_API_KEY'], // This is the default and can be omitted
});All examples below assume is already initialized as shown above.
clientjavascript
import Telnyx from 'telnyx';
const client = new Telnyx({
apiKey: process.env['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:
javascript
try {
const result = await client.messages.send({ to: '+13125550001', from: '+13125550002', text: 'Hello' });
} catch (err) {
if (err instanceof Telnyx.APIConnectionError) {
console.error('Network error — check connectivity and retry');
} else if (err instanceof Telnyx.RateLimitError) {
// 429: rate limited — wait and retry with exponential backoff
const retryAfter = err.headers?.['retry-after'] || 1;
await new Promise(r => setTimeout(r, retryAfter * 1000));
} else if (err instanceof Telnyx.APIError) {
console.error(`API error ${err.status}: ${err.message}`);
if (err.status === 422) {
console.error('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)而失败。在生产代码中请始终做好错误处理:
javascript
try {
const result = await client.messages.send({ to: '+13125550001', from: '+13125550002', text: 'Hello' });
} catch (err) {
if (err instanceof Telnyx.APIConnectionError) {
console.error('Network error — check connectivity and retry');
} else if (err instanceof Telnyx.RateLimitError) {
// 429: rate limited — wait and retry with exponential backoff
const retryAfter = err.headers?.['retry-after'] || 1;
await new Promise(r => setTimeout(r, retryAfter * 1000));
} else if (err instanceof Telnyx.APIError) {
console.error(`API error ${err.status}: ${err.message}`);
if (err.status === 422) {
console.error('Validation error — check required fields and formats');
}
}
}常见错误码: 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_idmessagesjavascript
const response = await client.calls.actions.addAIAssistantMessages('v3:550e8400-e29b-41d4-a716-446655440000_gRU1OGRkYQ');
console.log(response.data);Returns: (string)
result为通话中AI助手发起的会话添加消息。
POST /calls/{call_control_id}/actions/ai_assistant_add_messages可选参数: (字符串), (字符串), (对象数组)
client_statecommand_idmessagesjavascript
const response = await client.calls.actions.addAIAssistantMessages('v3:550e8400-e29b-41d4-a716-446655440000_gRU1OGRkYQ');
console.log(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_settingsjavascript
const response = await client.calls.actions.startAIAssistant('v3:550e8400-e29b-41d4-a716-446655440000_gRU1OGRkYQ');
console.log(response.data);Returns: (uuid), (string)
conversation_idresult在通话中启动AI助手。预期触发的Webhook:
call.conversation.endedcall.conversation_insights.generated
POST /calls/{call_control_id}/actions/ai_assistant_start可选参数: (对象), (字符串), (字符串), (字符串), (对象), (对象数组), (对象数组), (布尔值), (对象), (字符串), (对象)
assistantclient_statecommand_idgreetinginterruption_settingsmessage_historyparticipantssend_message_history_updatestranscriptionvoicevoice_settingsjavascript
const response = await client.calls.actions.startAIAssistant('v3:550e8400-e29b-41d4-a716-446655440000_gRU1OGRkYQ');
console.log(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_idjavascript
const response = await client.calls.actions.stopAIAssistant('v3:550e8400-e29b-41d4-a716-446655440000_gRU1OGRkYQ');
console.log(response.data);Returns: (string)
result停止通话中的AI助手。
POST /calls/{call_control_id}/actions/ai_assistant_stop可选参数: (字符串), (字符串)
client_statecommand_idjavascript
const response = await client.calls.actions.stopAIAssistant('v3:550e8400-e29b-41d4-a716-446655440000_gRU1OGRkYQ');
console.log(response.data);返回值: (字符串)
resultGather
采集
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_digitsjavascript
const response = await client.calls.actions.gather('v3:550e8400-e29b-41d4-a716-446655440000_gRU1OGRkYQ');
console.log(response.data);Returns: (string)
result采集DTMF信号以构建交互式菜单。你可以传入有效数字列表。命令必须在命令之后执行。
gatherAnswerPOST /calls/{call_control_id}/actions/gather可选参数: (字符串), (字符串), (字符串), (32位整数), (32位整数), (32位整数), (32位整数), (字符串), (32位整数), (字符串)
client_statecommand_idgather_idinitial_timeout_millisinter_digit_timeout_millismaximum_digitsminimum_digitsterminating_digittimeout_millisvalid_digitsjavascript
const response = await client.calls.actions.gather('v3:550e8400-e29b-41d4-a716-446655440000_gRU1OGRkYQ');
console.log(response.data);返回值: (字符串)
resultGather stop
停止采集
Stop current gather. Expected Webhooks:
call.gather.ended
POST /calls/{call_control_id}/actions/gather_stopOptional: (string), (string)
client_statecommand_idjavascript
const response = await client.calls.actions.stopGather('v3:550e8400-e29b-41d4-a716-446655440000_gRU1OGRkYQ');
console.log(response.data);Returns: (string)
result停止当前采集操作。预期触发的Webhook:
call.gather.ended
POST /calls/{call_control_id}/actions/gather_stop可选参数: (字符串), (字符串)
client_statecommand_idjavascript
const response = await client.calls.actions.stopGather('v3:550e8400-e29b-41d4-a716-446655440000_gRU1OGRkYQ');
console.log(response.data);返回值: (字符串)
resultGather using AI
使用AI采集
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_settingsjavascript
const response = await client.calls.actions.gatherUsingAI('call_control_id', {
parameters: {
properties: 'bar',
required: 'bar',
type: 'bar',
},
});
console.log(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_settingsjavascript
const response = await client.calls.actions.gatherUsingAI('call_control_id', {
parameters: {
properties: 'bar',
required: 'bar',
type: 'bar',
},
});
console.log(response.data);返回值: (uuid), (字符串)
conversation_idresultGather using audio
使用音频采集
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_digitsjavascript
const response = await client.calls.actions.gatherUsingAudio('v3:550e8400-e29b-41d4-a716-446655440000_gRU1OGRkYQ');
console.log(response.data);Returns: (string)
result在通话中播放音频文件,直到采集到所需的DTMF信号以构建交互式菜单。你可以传入有效数字列表以及,该音频会在每次提示开始时播放。收到DTMF信号时会中断播放。
invalid_audio_urlPOST /calls/{call_control_id}/actions/gather_using_audio可选参数: (字符串), (字符串), (字符串), (32位整数), (字符串), (字符串), (32位整数), (32位整数), (字符串), (32位整数), (字符串), (32位整数), (字符串)
audio_urlclient_statecommand_idinter_digit_timeout_millisinvalid_audio_urlinvalid_media_namemaximum_digitsmaximum_triesmedia_nameminimum_digitsterminating_digittimeout_millisvalid_digitsjavascript
const response = await client.calls.actions.gatherUsingAudio('v3:550e8400-e29b-41d4-a716-446655440000_gRU1OGRkYQ');
console.log(response.data);返回值: (字符串)
resultGather using speak
使用语音合成采集
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_settingsjavascript
const response = await client.calls.actions.gatherUsingSpeak('call_control_id', {
payload: 'say this on call',
voice: 'male',
});
console.log(response.data);Returns: (string)
result将文本转换为语音并在通话中播放,直到采集到所需的DTMF信号以构建交互式菜单。你可以传入有效数字列表以及,该内容会在每次提示开始时播放。收到DTMF信号时会中断语音播放。
invalid_payloadPOST /calls/{call_control_id}/actions/gather_using_speakvoicepayload可选参数: (字符串), (字符串), (32位整数), (字符串), (枚举值: 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), (32位整数), (32位整数), (32位整数), (枚举值: text, ssml), (枚举值: basic, premium), (字符串), (32位整数), (字符串), (对象)
client_statecommand_idinter_digit_timeout_millisinvalid_payloadlanguagemaximum_digitsmaximum_triesminimum_digitspayload_typeservice_levelterminating_digittimeout_millisvalid_digitsvoice_settingsjavascript
const response = await client.calls.actions.gatherUsingSpeak('call_control_id', {
payload: 'say this on call',
voice: 'male',
});
console.log(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-timestampjavascript
// In your webhook handler (e.g., Express — use raw body, not parsed JSON):
app.post('/webhooks', express.raw({ type: 'application/json' }), async (req, res) => {
try {
const event = await client.webhooks.unwrap(req.body.toString(), {
headers: req.headers,
});
// Signature valid — event is the parsed webhook payload
console.log('Received event:', event.data.event_type);
res.status(200).send('OK');
} catch (err) {
console.error('Webhook verification failed:', err.message);
res.status(400).send('Invalid signature');
}
});The following webhook events are sent to your configured webhook URL.
All webhooks include and headers for Ed25519 signature verification. Use to verify.
telnyx-timestamptelnyx-signature-ed25519client.webhooks.unwrap()| Event | Description |
|---|---|
| Call AI Gather Ended |
| Call AI Gather Message History Updated |
| Call AI Gather Partial Results |
| Call Gather Ended |
Telnyx使用Ed25519对Webhook进行签名。每个请求都包含和头。生产环境中请始终验证签名:
telnyx-signature-ed25519telnyx-timestampjavascript
// In your webhook handler (e.g., Express — use raw body, not parsed JSON):
app.post('/webhooks', express.raw({ type: 'application/json' }), async (req, res) => {
try {
const event = await client.webhooks.unwrap(req.body.toString(), {
headers: req.headers,
});
// Signature valid — event is the parsed webhook payload
console.log('Received event:', event.data.event_type);
res.status(200).send('OK');
} catch (err) {
console.error('Webhook verification failed:', err.message);
res.status(400).send('Invalid signature');
}
});以下Webhook事件会发送到你配置的Webhook地址。所有Webhook都包含和头用于Ed25519签名验证,可使用完成验证。
telnyx-timestamptelnyx-signature-ed25519client.webhooks.unwrap()| 事件 | 描述 |
|---|---|
| 通话AI采集结束 |
| 通话AI采集消息历史更新 |
| 通话AI采集部分结果 |
| 通话采集结束 |
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 | 标识资源类型 |
| date-time | 事件发生的ISO 8601格式时间戳 |
| 字符串 | 用于通过通话控制API下发指令的通话ID |
| 字符串 | 通话使用的Telnyx连接ID |
| 字符串 | 通话唯一ID,可用于关联Webhook事件 |
| 字符串 | 通话会话唯一ID,可用于关联Webhook事件 |
| 字符串 | 从指令中获取的状态 |
| 字符串 | 发起通话的号码或SIP URI |
| 字符串 | 通话的目标号码或SIP URI |
| 对象数组 | AI采集过程中交换的消息历史 |
| 对象 | AI采集的结果,其类型取决于指令中提供的 |
| 枚举: valid, invalid | 反映指令结束的状态 |
CallAIGatherMessageHistoryUpdated| 字段 | 类型 | 描述 |
|---|---|---|
| 枚举: event | 标识资源类型 |
| 枚举: call.ai_gather.message_history_updated | 所投递的事件类型 |
| uuid | 标识资源类型 |
| date-time | 事件发生的ISO 8601格式时间戳 |
| 字符串 | 用于通过通话控制API下发指令的通话ID |
| 字符串 | 通话使用的Telnyx连接ID |
| 字符串 | 通话唯一ID,可用于关联Webhook事件 |
| 字符串 | 通话会话唯一ID,可用于关联Webhook事件 |
| 字符串 | 从指令中获取的状态 |
| 字符串 | 发起通话的号码或SIP URI |
| 字符串 | 通话的目标号码或SIP URI |
| 对象数组 | AI采集过程中交换的消息历史 |
CallAIGatherPartialResults| 字段 | 类型 | 描述 |
|---|---|---|
| 枚举: event | 标识资源类型 |
| 枚举: call.ai_gather.partial_results | 所投递的事件类型 |
| uuid | 标识资源类型 |
| date-time | 事件发生的ISO 8601格式时间戳 |
| 字符串 | 用于通过通话控制API下发指令的通话ID |
| 字符串 | 通话使用的Telnyx连接ID |
| 字符串 | 通话唯一ID,可用于关联Webhook事件 |
| 字符串 | 通话会话唯一ID,可用于关联Webhook事件 |
| 字符串 | 从指令中获取的状态 |
| 字符串 | 发起通话的号码或SIP URI |
| 字符串 | 通话的目标号码或SIP URI |
| 对象数组 | AI采集过程中交换的消息历史 |
| 对象 | AI采集的部分结果,其类型取决于指令中提供的 |
callGatherEnded| 字段 | 类型 | 描述 |
|---|---|---|
| 枚举: event | 标识资源类型 |
| 枚举: call.gather.ended | 所投递的事件类型 |
| uuid | 标识资源类型 |
| 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 | 反映指令结束的状态 |