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 telnyx
bash
npm install telnyx

Setup

配置

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
client
is already initialized as shown above.
javascript
import Telnyx from 'telnyx';

const client = new Telnyx({
  apiKey: process.env['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:
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:
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)而失败。在生产代码中请始终做好错误处理:
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');
    }
  }
}
常见错误码:
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])
javascript
const response = await client.calls.actions.addAIAssistantMessages('v3:550e8400-e29b-41d4-a716-446655440000_gRU1OGRkYQ');

console.log(response.data);
Returns:
result
(string)
为通话中AI助手发起的会话添加消息。
POST /calls/{call_control_id}/actions/ai_assistant_add_messages
可选参数:
client_state
(字符串),
command_id
(字符串),
messages
(对象数组)
javascript
const response = await client.calls.actions.addAIAssistantMessages('v3:550e8400-e29b-41d4-a716-446655440000_gRU1OGRkYQ');

console.log(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)
javascript
const response = await client.calls.actions.startAIAssistant('v3:550e8400-e29b-41d4-a716-446655440000_gRU1OGRkYQ');

console.log(response.data);
Returns:
conversation_id
(uuid),
result
(string)
在通话中启动AI助手。预期触发的Webhook:
  • 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
(对象)
javascript
const response = await client.calls.actions.startAIAssistant('v3:550e8400-e29b-41d4-a716-446655440000_gRU1OGRkYQ');

console.log(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)
javascript
const response = await client.calls.actions.stopAIAssistant('v3:550e8400-e29b-41d4-a716-446655440000_gRU1OGRkYQ');

console.log(response.data);
Returns:
result
(string)
停止通话中的AI助手。
POST /calls/{call_control_id}/actions/ai_assistant_stop
可选参数:
client_state
(字符串),
command_id
(字符串)
javascript
const response = await client.calls.actions.stopAIAssistant('v3:550e8400-e29b-41d4-a716-446655440000_gRU1OGRkYQ');

console.log(response.data);
返回值:
result
(字符串)

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)
javascript
const response = await client.calls.actions.gather('v3:550e8400-e29b-41d4-a716-446655440000_gRU1OGRkYQ');

console.log(response.data);
Returns:
result
(string)
采集DTMF信号以构建交互式菜单。你可以传入有效数字列表。
gather
命令必须在
Answer
命令之后执行。
POST /calls/{call_control_id}/actions/gather
可选参数:
client_state
(字符串),
command_id
(字符串),
gather_id
(字符串),
initial_timeout_millis
(32位整数),
inter_digit_timeout_millis
(32位整数),
maximum_digits
(32位整数),
minimum_digits
(32位整数),
terminating_digit
(字符串),
timeout_millis
(32位整数),
valid_digits
(字符串)
javascript
const response = await client.calls.actions.gather('v3:550e8400-e29b-41d4-a716-446655440000_gRU1OGRkYQ');

console.log(response.data);
返回值:
result
(字符串)

Gather stop

停止采集

Stop current gather. Expected Webhooks:
  • call.gather.ended
POST /calls/{call_control_id}/actions/gather_stop
Optional:
client_state
(string),
command_id
(string)
javascript
const response = await client.calls.actions.stopGather('v3:550e8400-e29b-41d4-a716-446655440000_gRU1OGRkYQ');

console.log(response.data);
Returns:
result
(string)
停止当前采集操作。预期触发的Webhook:
  • call.gather.ended
POST /calls/{call_control_id}/actions/gather_stop
可选参数:
client_state
(字符串),
command_id
(字符串)
javascript
const response = await client.calls.actions.stopGather('v3:550e8400-e29b-41d4-a716-446655440000_gRU1OGRkYQ');

console.log(response.data);
返回值:
result
(字符串)

Gather 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_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)
javascript
const response = await client.calls.actions.gatherUsingAI('call_control_id', {
  parameters: {
    properties: 'bar',
    required: 'bar',
    type: 'bar',
  },
});

console.log(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
(对象)
javascript
const response = await client.calls.actions.gatherUsingAI('call_control_id', {
  parameters: {
    properties: 'bar',
    required: 'bar',
    type: 'bar',
  },
});

console.log(response.data);
返回值:
conversation_id
(uuid),
result
(字符串)

Gather 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_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)
javascript
const response = await client.calls.actions.gatherUsingAudio('v3:550e8400-e29b-41d4-a716-446655440000_gRU1OGRkYQ');

console.log(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
(32位整数),
invalid_audio_url
(字符串),
invalid_media_name
(字符串),
maximum_digits
(32位整数),
maximum_tries
(32位整数),
media_name
(字符串),
minimum_digits
(32位整数),
terminating_digit
(字符串),
timeout_millis
(32位整数),
valid_digits
(字符串)
javascript
const response = await client.calls.actions.gatherUsingAudio('v3:550e8400-e29b-41d4-a716-446655440000_gRU1OGRkYQ');

console.log(response.data);
返回值:
result
(字符串)

Gather 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_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)
javascript
const response = await client.calls.actions.gatherUsingSpeak('call_control_id', {
  payload: 'say this on call',
  voice: 'male',
});

console.log(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
(32位整数),
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
(32位整数),
maximum_tries
(32位整数),
minimum_digits
(32位整数),
payload_type
(枚举值: text, ssml),
service_level
(枚举值: basic, premium),
terminating_digit
(字符串),
timeout_millis
(32位整数),
valid_digits
(字符串),
voice_settings
(对象)
javascript
const response = await client.calls.actions.gatherUsingSpeak('call_control_id', {
  payload: 'say this on call',
  voice: 'male',
});

console.log(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:
javascript
// 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
telnyx-timestamp
and
telnyx-signature-ed25519
headers for Ed25519 signature verification. Use
client.webhooks.unwrap()
to verify.
EventDescription
CallAIGatherEnded
Call AI Gather Ended
CallAIGatherMessageHistoryUpdated
Call AI Gather Message History Updated
CallAIGatherPartialResults
Call AI Gather Partial Results
callGatherEnded
Call Gather Ended
Telnyx使用Ed25519对Webhook进行签名。每个请求都包含
telnyx-signature-ed25519
telnyx-timestamp
头。生产环境中请始终验证签名:
javascript
// 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都包含
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标识资源类型
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采集过程中交换的消息历史
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标识资源类型
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采集过程中交换的消息历史
CallAIGatherPartialResults
字段类型描述
data.record_type
枚举: event标识资源类型
data.event_type
枚举: call.ai_gather.partial_results所投递的事件类型
data.id
uuid标识资源类型
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采集过程中交换的消息历史
data.payload.partial_results
对象AI采集的部分结果,其类型取决于指令中提供的
parameters
callGatherEnded
字段类型描述
data.record_type
枚举: event标识资源类型
data.event_type
枚举: call.gather.ended所投递的事件类型
data.id
uuid标识资源类型
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反映指令结束的状态