Skip to main content

Relay.Calling.Call

All calls in SignalWire have a common generic interface, Relay.Calling.Call. A Relay.Calling.Call is a connection between SignalWire and another device.

Properties

PropertyTypeDescription
idstringThe unique identifier of the call
typestringThe type of call. Only phone and sip are currently supported
fromstringThe phone number that the call is coming from
tostringThe phone number you are attempting to call
timeoutnumberThe seconds the call rings before being transferred to voicemail
statestringThe current state of the call. See State Events for all the possible call states
prevStatestringThe previous state of the call
contextstringThe context the call belongs to
peerRelay.Calling.CallThe call your original call is connected to
activebooleanWhether the call is active
endedbooleanWhether the call has ended
answeredbooleanWhether the call has been answered
failedbooleanWhether the call has failed
busybooleanWhether the call was busy

Methods

amd

Alias for detectAnsweringMachine.

amdAsync

Alias for detectAnsweringMachineAsync.

answer

Answer an inbound call.

Parameters

None

Returns

Promise<Relay.Calling.AnswerResult> - Promise object that will be fulfilled with a Relay.Calling.AnswerResult object.

Examples

Answer an inbound call and check if it was successful.

// within an async function ..
const answerResult = await call.answer()
if (answerResult.successful) {

}

connect

Attempt to connect an existing call to a new outbound call and waits until one of the remote party picks the call or the connect fails.

This method involves complex nested parameters. You can connect to multiple devices in series, parallel, or any combination of both with creative use of the parameters. Series implies one device at a time, while parallel implies multiple devices at the same time.

Parameters

ParameterTypeRequiredDescription
paramsobjectObject with the following properties:
devicesarrayOne or more objects with the structure below. Nested depends on whether to dial in serial or parallel.
ringbackobjectoptionalRingback audio to play to call leg. You can play audio, tts, silence or ringtone. See play media parameter for details.
  • Structure of a device:
ParameterTypeRequiredDescription
typestringThe device type. Only phone and sip are currently supported
fromstringoptionalThe party the call is coming from. If not provided, the SDK will use the from of the originator call. Must be a SignalWire number or SIP endpoint that you own.
tostringThe party you are attempting to connect with
timeoutnumberoptionalThe time, in seconds, the call will ring before going to voicemail
headers{name: string, value: string}[]optionalSIP only. Array of headers. Must be X- headers only
codecsstringoptionalSIP only. Optional array of desired codecs in order of preference. Supported values are PCMU, PCMA, OPUS, G729, G722, VP8, H264. Default is parent leg codec(s)
webrtc_mediabooleanoptionalSIP only. If true, WebRTC media is negotiated. Default is parent leg setting

Returns

Promise<Relay.Calling.ConnectResult> - Promise object that will be fulfilled with a Relay.Calling.ConnectResult object.

Examples

Try connecting by calling +18991114444 and +18991114445 in series.

const connectResult = await call.connect(
{ type: 'phone', to: '+18991114444', timeout: 30 },
{ type: 'phone', to: '+18991114445', timeout: 20 }
)

if (connectResult.successful) {
// connectResult.call is the remote leg connected with yours.
}

Combine serial and parallel calling. Call +18991114443 first and - if it doesn't answer - try calling in parallel +18991114444 and +18991114445. If none of the devices answer, continue the same process with +18991114446 and +18991114447.

const result = await call.connect(
{ type: 'phone', to: '+18991114443', timeout: 30 },
[
{ type: 'phone', to: '+18991114444', timeout: 30 },
{ type: 'phone', to: '+18991114445', timeout: 20 }
],
[
{ type: 'phone', to: '+18991114446', timeout: 30 },
{ type: 'phone', to: '+18991114447', timeout: 20 }
]
)

if (connectResult.successful) {
// connectResult.call is the remote leg connected with yours.
}

Try connecting by calling +18991114444 and +18991114445 in series playing the US ringtone.

const params = {
devices: [
{ type: 'phone', to: '+18991114444' },
{ type: 'phone', to: '+18991114445' }
],
ringback: { type: 'ringtone', name: 'us' }
}
const connectResult = await call.connect(params)
if (connectResult.successful) {
// connectResult.call is the remote leg connected with yours.
}

connectAsync

Asynchronous version of connect. It does not wait the connect to completes or fails but returns a Relay.Calling.ConnectAction you can interact with.

Parameters

See connect for the parameter list.

Returns

Promise<Relay.Calling.ConnectAction> - Promise object that will be fulfilled with a Relay.Calling.ConnectAction object.

Examples

Trying to connect a call by calling in series +18991114444 and +18991114445.

async function main() {
const connectAction = await call.connectAsync(
{ type: 'phone', to: '+18991114444', timeout: 30 },
{ type: 'phone', to: '+18991114445', timeout: 20 }
)
// .. do other important things while Relay try to connect your call..

// Check whether the action has completed
if (connectAction.completed) {

}
}

main().catch(console.error)

faxReceive

Prepare the call to receive an inbound fax. It waits until the fax has been received or failed.

Parameters

None

Returns

Promise<Relay.Calling.FaxResult> - Promise object that will be fulfilled with a Relay.Calling.FaxResult object.

Examples

Receiving a fax on the call and print logs for URL and number of received pages.

async function main() {
const faxResult = await call.faxReceive()
if (faxResult.successful) {
console.log('URL: ', faxResult.document)
console.log('Total pages: ', faxResult.pages)
}
}

main().catch(console.error)

faxReceiveAsync

Asynchronous version of faxReceive. It does not wait the fax to be received but returns a Relay.Calling.FaxAction you can interact with.

Parameters

None

Returns

Promise<Relay.Calling.FaxAction> - Promise object that will be fulfilled with a Relay.Calling.FaxAction object.

Examples

Trying to receive a fax. Stop the attempt after 5 seconds.

async function main() {
const faxAction = await call.faxReceiveAsync()

setTimeout(async () => {
await faxAction.stop()
}, 5000)
}

main().catch(console.error)

faxSend

Send a Fax through the call. It waits until the fax has been sent or failed.

Parameters

ParameterTypeRequiredDescription
documentstringHttp(s) URL to the document to send. PDF format only.
identitystringoptionalIdentity to display on receiving fax. Defaults to SignalWire DID.

Returns

Promise<Relay.Calling.FaxResult> - Promise object that will be fulfilled with a Relay.Calling.FaxResult object.

Examples

Sending a fax on the call and print logs the number of sent pages.

async function main() {
const faxResult = await call.faxSend('https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf', null, 'Custom Header')
if (faxResult.successful) {
console.log('URL: ', faxResult.document)
console.log('Total pages: ', faxResult.pages)
}
}

main().catch(console.error)

faxSendAsync

Asynchronous version of faxSend. It does not wait the fax to be sent but returns a Relay.Calling.FaxAction you can interact with.

Parameters

See faxSend for the parameter list.

Returns

Promise<Relay.Calling.FaxAction> - Promise object that will be fulfilled with a Relay.Calling.FaxAction object.

Examples

Trying to send a fax. Stop sending it after 5 seconds.

async function main() {
const faxAction = await call.faxSendAsync('https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf', null, 'Custom Header')

setTimeout(async () => {
await faxAction.stop()
}, 5000)
}

main().catch(console.error)

dial

This will start a call that was created with newCall and waits until the Call has been answered or hung up.

Parameters

None

Returns

Promise<Relay.Calling.DialResult> - Promise object that will be fulfilled with a Relay.Calling.DialResult object.

Examples

async function main() {
const call = client.calling.newCall({ type: 'phone', from: '+1XXXXXXXXXX', to: '+1YYYYYYYYYY' })

const dialResult = await call.dial()
}

main().catch(console.error)

hangup

Hangup the call.

Parameters

None

Returns

Promise<Relay.Calling.HangupResult> - Promise object that will be fulfilled with a Relay.Calling.HangupResult object.

Examples

Hangup a call and check if it was successful.

// within an async function ..
const hangupResult = await call.hangup()
if (hangupResult.successful) {

}

play

Play one or multiple media in a Call and waits until the playing has ended.

The play method is a generic method for all types of playing, see playAudio, playSilence, playTTS or playRingtone for more specific usage.

Parameters

ParameterTypeRequiredDescription
paramsobjectObject with the following properties:
volumenumberoptionalVolume value between -40dB and +40dB where 0 is unchanged. Default is 0.
mediaarrayArray of media objects to play. See below for each type:
  • To play an audio file:
ParameterTypeRequiredDescription
typestringaudio
urlstringHttp(s) URL to audio resource to play
  • To play a text to speech string:
ParameterTypeRequiredDescription
typestringtts
textstringTTS to play
languagestringoptionalDefault to en-US
genderstringoptionalmale or female. Default to female
  • To play silence:
ParameterTypeRequiredDescription
typestringsilence
durationnumberSeconds of silence to play
  • To play ringtone:
ParameterTypeRequiredDescription
typestringringtone
namestringThe name of the ringtone. See ringtones for the supported values
durationnumberoptionalDuration of ringtone to play. Default to 1 ringtone iteration.

Returns

Promise<Relay.Calling.PlayResult> - Promise object that will be fulfilled with a Relay.Calling.PlayResult object.

Examples

Play multiple media in one request setting volume to 6dB.

async function main() {
const params = {
media: [
{ type: 'tts', text: 'Listen this awesome file!' },
{ type: 'audio', url: 'https://cdn.signalwire.com/default-music/welcome.mp3' },
{ type: 'silence', duration: 5 },
{ type: 'tts', text: 'Did you like it?' }
],
volume: 6
}
const playResult = await call.play(params)
}

main().catch(console.error)

playAsync

Asynchronous version of play. It does not wait the playing to completes but returns a Relay.Calling.PlayAction you can interact with.

Parameters

See play for the parameter list.

Returns

Promise<Relay.Calling.PlayAction> - Promise object that will be fulfilled with a Relay.Calling.PlayAction object.

Examples

Play multiple media elements in the call and stop them after 5 seconds.

async function main() {
const params = {
media: [
{ type: 'tts', text: 'Listen this awesome file!' },
{ type: 'audio', url: 'https://cdn.signalwire.com/default-music/welcome.mp3' },
{ type: 'silence', duration: 5 },
{ type: 'tts', text: 'Did you like it?' }
],
volume: 6
}
const playAction = await call.playAsync(params)

setTimeout(async () => {
await playAction.stop()
}, 5000)
}

main().catch(console.error)

playAudio

This is a helper function that refines the use of play. This simplifies playing an audio file.

Parameters

ParameterTypeRequiredDescription
paramsobjectObject with the following properties:
urlstringHttp(s) URL to audio resource to play
volumenumberoptionalVolume value between -40dB and +40dB where 0 is unchanged. Default is 0.

Returns

Promise<Relay.Calling.PlayResult> - Promise object that will be fulfilled with a Relay.Calling.PlayResult object.

Examples

Play an Mp3 file using the signature with a string as parameter.

// within an async function ..
const playResult = await call.playAudio('https://cdn.signalwire.com/default-music/welcome.mp3')

Play an Mp3 file setting volume level to 4dB.

// within an async function ..
const params = {
url: 'https://cdn.signalwire.com/default-music/welcome.mp3',
volume: 4
}
const playResult = await call.playAudio(params)

playAudioAsync

Asynchronous version of playAudio. It does not wait the playing to completes but returns a Relay.Calling.PlayAction you can interact with.

Parameters

See playAudio for the parameter list.

Returns

Promise<Relay.Calling.PlayAction> - Promise object that will be fulfilled with a Relay.Calling.PlayAction object.

Examples

Play an Mp3 file and stop it after 5 seconds.

// within an async function ..
const playAction = await call.playAudioAsync('https://cdn.signalwire.com/default-music/welcome.mp3')

setTimeout(async () => {
await playAction.stop()
}, 5000)

playTTS

This is a helper function that refines the use of play. This simplifies playing TTS.

Parameters

ParameterTypeRequiredDescription
paramsobjectObject with the following properties:
textstringTTS to play
languagestringoptionalDefault to en-US
genderstringoptionalmale or female. Default to female
volumenumberoptionalVolume value between -40dB and +40dB where 0 is unchanged. Default is 0.

Returns

Promise<Relay.Calling.PlayResult> - Promise object that will be fulfilled with a Relay.Calling.PlayResult object.

Examples

Play TTS.

// within an async function ..
const playResult = await call.playTTS({ text: 'Welcome to SignalWire!', gender: 'male' })

playTTSAsync

Asynchronous version of playTTS. It does not wait the playing to completes but returns a Relay.Calling.PlayAction you can interact with.

Parameters

See playTTS for the parameter list.

Returns

Promise<Relay.Calling.PlayAction> - Promise object that will be fulfilled with a Relay.Calling.PlayAction object.

Examples

Play TTS and stop it after 5 seconds.

// within an async function ..
const playAction = await call.playTTSAsync({ text: 'Welcome to SignalWire!', gender: 'male' })

setTimeout(async () => {
await playAction.stop()
}, 5000)

playSilence

This is a helper function that refines the use of play. This simplifies playing silence.

Parameters

ParameterTypeRequiredDescription
durationnumberSeconds of silence to play

Returns

Promise<Relay.Calling.PlayResult> - Promise object that will be fulfilled with a Relay.Calling.PlayResult object.

Examples

Play silence for 10 seconds.

// within an async function ..
const playResult = await call.playSilence(10)

playSilenceAsync

Asynchronous version of playSilence. It does not wait the playing to completes but returns a Relay.Calling.PlayAction you can interact with.

Parameters

See playSilence for the parameter list.

Returns

Promise<Relay.Calling.PlayAction> - Promise object that will be fulfilled with a Relay.Calling.PlayAction object.

Examples

Play silence for 60 seconds, if Agent is available, stop the play.

// within an async function ..
const playAction = await call.playSilenceAsync(60)

if (Agent.available()) {
await playAction.stop()
}

playRingtone

This is a helper function that refines the use of play. This simplifies playing ringtones.

Parameters

ParameterTypeRequiredDescription
paramsobjectObject with the following properties:
namestringThe name of the ringtone. See ringtones for the supported values
durationnumberoptionalDuration of ringtone to play. Default to 1 ringtone iteration.
volumenumberoptionalVolume value between -40dB and +40dB where 0 is unchanged. Default is 0.

Returns

Promise<Relay.Calling.PlayResult> - Promise object that will be fulfilled with a Relay.Calling.PlayResult object.

Examples

Play a single US ringtone.

// within an async function ..
const playResult = await call.playRingtone({ name: 'us' })

playRingtoneAsync

Asynchronous version of playRingtone. It does not wait the playing to completes but returns a Relay.Calling.PlayAction you can interact with.

Parameters

See playRingtone for the parameter list.

Returns

Promise<Relay.Calling.PlayAction> - Promise object that will be fulfilled with a Relay.Calling.PlayAction object.

Examples

Play US ringtone for 30 seconds and stop it after 5 seconds.

// within an async function ..
const playAction = await call.playRingtoneAsync({ name: 'us', duration: 30 })

setTimeout(async () => {
await playAction.stop()
}, 5000)

detect

Start a detector on the call and waits until it has finished or failed.

The detect method is a generic method for all types of detecting, see detectAnsweringMachine, detectDigit or detectFax for more specific usage.

Parameters

ParameterTypeRequiredDescription
paramsobjectObject to tune the detector with the following properties:
  • To detect an answering machine:
ParameterTypeRequiredDescription
typestringmachine
timeoutnumberoptionalNumber of seconds to run the detector. Defaults to 30.0.
wait_for_beepbooleanoptionalWhether to wait until the AM is ready for voicemail delivery. Defaults to false.
initial_timeoutnumberoptionalNumber of seconds to wait for initial voice before giving up. Defaults to 4.5.
end_silence_timeoutnumberoptionalNumber of seconds to wait for voice to finish. Defaults to 1.0.
machine_voice_thresholdnumberoptionalHow many seconds of voice to decide is a machine. Defaults to 1.25.
machine_words_thresholdnumberoptionalHow many words to count to decide is a machine. Defaults to 6.
  • To detect digits:
ParameterTypeRequiredDescription
typestringdigit
timeoutnumberoptionalNumber of seconds to run the detector. Defaults to 30.0.
digitsstringoptionalThe digits to detect. Defaults to "0123456789#*".
  • To detect a fax:
ParameterTypeRequiredDescription
typestringfax
timeoutnumberoptionalNumber of seconds to run the detector. Defaults to 30.0.
tonestringoptionalThe fax tone to detect: CED or CNG. Defaults to "CED".

Returns

Promise<Relay.Calling.DetectResult> - Promise object that will be fulfilled with a Relay.Calling.DetectResult object.

Examples

Detect a machine with custom parameters and timeout.

// within an async function ..
const detectResult = await call.detect({ type: 'machine', timeout: 45, initial_timeout: 3 })
if (detectResult.successful) {

}

Detect a Fax setting timeout only.

// within an async function ..
const detectResult = await call.detect({ type: 'fax', timeout: 45 })
if (detectResult.successful) {

}

detectAsync

Asynchronous version of detect. It does not wait the detector ends but returns a Relay.Calling.DetectAction you can interact with.

Parameters

See detect for the parameter list.

Returns

Promise<Relay.Calling.DetectAction> - Promise object that will be fulfilled with a Relay.Calling.DetectAction object.

Examples

Detect all the digits using default parameters. Stop the action after 5 seconds.

async function main() {
call.on('detect.update', (call, params) => {
console.log('Detector event:', params)
})

const detectAction = await call.detectAsync('fax')
// Do other things while detector runs and then stop it..
setTimeout(async () => {
await detectAction.stop()
}, 5000)
}

main().catch(console.error)

detectAnsweringMachine

This is a helper function that refines the use of detect. The Promise will be resolved with a Relay.Calling.DetectResult object as soon as the detector decided who answered the call: MACHINE, HUMAN or UNKNOWN.

Parameters

ParameterTypeRequiredDescription
paramsobjectoptionalObject to tune the detector with the following properties:
timeoutnumberoptionalNumber of seconds to run the detector. Defaults to 30.0.
wait_for_beepbooleanoptionalWhether to wait until the AM is ready for voicemail delivery. Defaults to false.
initial_timeoutnumberoptionalNumber of seconds to wait for initial voice before giving up. Defaults to 4.5.
end_silence_timeoutnumberoptionalNumber of seconds to wait for voice to finish. Defaults to 1.0.
machine_voice_thresholdnumberoptionalHow many seconds of voice to decide is a machine. Defaults to 1.25.
machine_words_thresholdnumberoptionalHow many words to count to decide is a machine. Defaults to 6.

Returns

Promise<Relay.Calling.DetectResult> - Promise object that will be fulfilled with a Relay.Calling.DetectResult object.

Examples

Perform an AMD and wait until the machine is ready.

// within an async function ..
const { successful, result } = await call.detectAnsweringMachine({ wait_for_beep: true })
if (successful) {
console.log('AMD result:', result) // MACHINE || HUMAN || UNKNOWN
}

detectAnsweringMachineAsync

Asynchronous version of detectAnsweringMachine. It does not wait the detector ends but returns a Relay.Calling.DetectAction you can interact with.

Parameters

See detectAnsweringMachine for the parameter list.

Returns

Promise<Relay.Calling.DetectAction> - Promise object that will be fulfilled with a Relay.Calling.DetectAction object.

Examples

Perform an asynchronous AMD on the call. Then stop the action if not completed yet.

// within an async function ..
call.on('detect.update', (call, params) => {
// Handle a detector event here..
console.log(params)
})
const detectAction = await call.detectAnsweringMachineAsync()
// Do other things while detector runs and then stop it.
if (detectAction.completed) {
detectAction.stop()
}

detectDigit

This is a helper function that refines the use of detect. This simplifies detecting digits on a call.

Parameters

ParameterTypeRequiredDescription
paramsobjectoptionalObject to tune the detector with the following properties:
timeoutnumberoptionalNumber of seconds to run the detector. Defaults to 30.0.
digitsstringoptionalThe digits to detect. Defaults to "0123456789#*".

Returns

Promise<Relay.Calling.DetectResult> - Promise object that will be fulfilled with a Relay.Calling.DetectResult object.

Examples

Detect digits and then write a log with the result.

// within an async function ..
const detectResult = await call.detectDigit()
if (detectResult.successful) {
console.log('Digits detected:', detectResult.result)
}

detectDigitAsync

Asynchronous version of detectDigit. It does not wait the detector ends but returns a Relay.Calling.DetectAction you can interact with.

Parameters

See detectDigit for the parameter list.

Returns

Promise<Relay.Calling.DetectAction> - Promise object that will be fulfilled with a Relay.Calling.DetectAction object.

Examples

Detect only 1-3 digits. Stop the action after 5 seconds.

async function main() {
const detectAction = await call.detectDigitAsync({ digits: '123' })

setTimeout(async () => {
await detectAction.stop()
}, 5000)
}

main().catch(console.error)

detectFax

This is a helper function that refines the use of detect. This simplifies detecting a fax.

Parameters

ParameterTypeRequiredDescription
paramsobjectoptionalObject to tune the detector with the following properties:
timeoutnumberoptionalNumber of seconds to run the detector. Defaults to 30.0.
tonestringoptionalThe fax tone to detect: CED or CNG. Defaults to "CED".

Returns

Promise<Relay.Calling.DetectResult> - Promise object that will be fulfilled with a Relay.Calling.DetectResult object.

Examples

Detect fax on the current call.

// within an async function ..
const detectResult = await call.detectFax()
if (detectResult.successful) {
// A fax has been detected!
}

detectFaxAsync

Asynchronous version of detectFax. It does not wait the detector ends but returns a Relay.Calling.DetectAction you can interact with.

Parameters

See detectFax for the parameter list.

Returns

Promise<Relay.Calling.DetectAction> - Promise object that will be fulfilled with a Relay.Calling.DetectAction object.

Examples

Detect fax on the current call. Stop the action after 5 seconds.

async function main() {
const detectAction = await call.detectFaxAsync()

setTimeout(async () => {
await detectAction.stop()
}, 5000)
}

main().catch(console.error)

prompt

Play one or multiple media while collecting user's input from the call at the same time, such as digits and speech. It waits until the collection succeed or timeout is reached.

The prompt method is a generic method, see promptAudio, promptTTS or promptRingtone for more specific usage.

Parameters

ParameterTypeRequiredDescription
paramsobjectObject with the following properties:
typestringdigits, speech or both
mediaarrayList of media elements to play. See play parameters for the object structure
initial_timeoutnumberoptionalInitial timeout in seconds. Default to 4 seconds.
volumenumberoptionalVolume value between -40dB and +40dB where 0 is unchanged. Default is 0.
  • To collect digits:
ParameterTypeRequiredDescription
digits_maxnumberMax digits to collect
digits_terminatorsstringoptionalDTMF digits that will end the recording. Default not set.
digits_timeoutnumberoptionalTimeout in seconds between each digit
  • To collect speech:
ParameterTypeRequiredDescription
end_silence_timeoutnumberoptionalHow much silence to wait for end of speech. Default to 1 second.
speech_timeoutnumberoptionalMaximum time to collect speech. Default to 60 seconds.
speech_languagestringoptionalLanguage to detect. Default to en-US.
speech_hintsarrayoptionalArray of expected phrases to detect

Returns

Promise<Relay.Calling.PromptResult> - Promise object that will be fulfilled with a Relay.Calling.PromptResult object.

Examples

Ask user to enter their PIN and collect the digits.

async function main() {
const params = {
type: 'digits',
digits_max: 4,
digits_terminators: '#',
media: [
{ type: 'tts', text: 'Welcome at SignalWire. Please, enter your PIN and then # to proceed' }
]
}
const promptResult = await call.prompt(params)

if (promptResult.successful) {
const type = promptResult.type // digit
const pin = promptResult.result // pin entered by the user
}
}

main().catch(console.error)

promptAsync

Asynchronous version of prompt. It does not wait the collection to completes but returns a Relay.Calling.PromptAction you can interact with.

Parameters

See prompt for the parameter list.

Returns

Promise<Relay.Calling.PromptAction> - Promise object that will be fulfilled with a Relay.Calling.PromptAction object.

Examples

Ask user to enter their PIN and collect the digits.

async function main() {
const params = {
type: 'digits',
digits_max: 4,
digits_terminators: '#',
media: [
{ type: 'tts', text: 'Welcome at SignalWire. Please, enter your PIN and then # to proceed' },
{ type: 'audio', url: 'https://cdn.signalwire.com/default-music/welcome.mp3' }
]
}
const promptAction = await call.promptAsync(params)
// .. do other important things while collecting user digits..

if (promptAction.completed) {
const result = promptAction.result // => PromptResult object
}
}

main().catch(console.error)

promptAudio

This is a helper function that refines the use of prompt. This function simplifies playing an audio file while collecting user's input from the call, such as digits and speech.

Parameters

You can set all the properties that prompt accepts replacing media with:

ParameterTypeRequiredDescription
urlstringHttp(s) URL to audio resource to play

The SDK will build the media for you.

Returns

Promise<Relay.Calling.PromptResult> - Promise object that will be fulfilled with a Relay.Calling.PromptResult object.

Examples

Collect user's digits while playing an Mp3 file.

async function main() {
const params = {
type: 'digits',
digits_max: 4,
url: 'https://cdn.signalwire.com/default-music/welcome.mp3'
}
const promptResult = await call.promptAudio(params)

if (promptResult.successful) {
const type = promptResult.type // digit
const digits = promptResult.result // digits entered by the user
}
}

main().catch(console.error)

promptAudioAsync

Asynchronous version of promptAudio. It does not wait the collection to completes but returns a Relay.Calling.PromptAction you can interact with.

Parameters

See promptAudio for the parameter list.

Returns

Promise<Relay.Calling.PromptAction> - Promise object that will be fulfilled with a Relay.Calling.PromptAction object.

Examples

Ask user to enter their PIN and collect the digits.

async function main() {
const params = {
type: 'digits',
digits_max: 4,
url: 'https://cdn.signalwire.com/default-music/welcome.mp3'
}
const promptAction = await call.promptAudioAsync(params)
// .. do other important things while collecting user digits..

if (promptAction.completed) {
const result = promptAction.result // => PromptResult object
}
}

main().catch(console.error)

promptTTS

This is a helper function that refines the use of prompt. This function simplifies playing TTS while collecting user's input from the call, such as digits and speech.

Parameters

You can set all the properties that prompt accepts replacing media with:

ParameterTypeRequiredDescription
textstringText-to-speech string to play
languagestringoptionalDefault to en-US
genderstringoptionalmale or female. Default to female

The SDK will build the media for you.

Returns

Promise<Relay.Calling.PromptResult> - Promise object that will be fulfilled with a Relay.Calling.PromptResult object.

Examples

Ask user to enter their PIN and collect the digits.

async function main() {
const params = {
type: 'digits',
digits_max: 3,
text: 'Please, enter your 3 digit PIN',
gender: 'male'
}
const promptResult = await call.promptTTS(params)
if (promptResult.successful) {
const type = promptResult.type // digit
const pin = promptResult.result // pin entered by the user
}
}

main().catch(console.error)

promptTTSAsync

Asynchronous version of promptTTS. It does not wait the collection to completes but returns a Relay.Calling.PromptAction you can interact with.

Parameters

See promptTTS for the parameter list.

Returns

Promise<Relay.Calling.PromptAction> - Promise object that will be fulfilled with a Relay.Calling.PromptAction object.

Examples

Ask user to enter their PIN and collect the digits.

async function main() {
const params = {
type: 'digits',
digits_max: 3,
text: 'Please, enter your 3 digit PIN',
gender: 'male'
}
const promptAction = await call.promptTTSAsync(params)
// .. do other important things while collecting user digits..

if (promptAction.completed) {
const result = promptAction.result // => PromptResult object
}
}

main().catch(console.error)

detectHuman

This is a helper function that refines the use of detect. This simplifies detecting a human on the call and is the inverse of detectMachine.

Deprecated since: v2.2 - Use detectAnsweringMachine instead.

Parameters

ParameterTypeRequiredDescription
paramsobjectrequiredObject to tune the detector with the following properties:
timeoutnumberoptionalNumber of seconds to run the detector. Defaults to 30.0.
wait_for_beepbooleanoptionalWhether to wait until the AM is ready for voicemail delivery. Defaults to false.
initial_timeoutnumberoptionalNumber of seconds to wait for initial voice before giving up. Defaults to 4.5.
end_silence_timeoutnumberoptionalNumber of seconds to wait for voice to finish. Defaults to 1.0.
machine_voice_thresholdnumberoptionalHow many seconds of voice to decide is a machine. Defaults to 1.25.
machine_words_thresholdnumberoptionalHow many words to count to decide is a machine. Defaults to 6.

Returns

Promise<Relay.Calling.DetectResult> - Promise object that will be fulfilled with a Relay.Calling.DetectResult object.

Examples

Detect a human on the current call.

// within an async function ..
const detectResult = await call.detectHuman()
if (detectResult.successful) {
// Human has been detected!
}

detectHumanAsync

Asynchronous version of detectHuman. It does not wait the detector ends but returns a Relay.Calling.DetectAction you can interact with.

Deprecated since: v2.2 - Use detectAnsweringMachineAsync instead.

Parameters

See detectHuman for the parameter list.

Returns

Promise<Relay.Calling.DetectAction> - Promise object that will be fulfilled with a Relay.Calling.DetectAction object.

Examples

Detect a human on the current call. Stop the action after 5 seconds.

async function main() {
const detectAction = await call.detectHumanAsync()

setTimeout(async () => {
await detectAction.stop()
}, 5000)
}

main().catch(console.error)

detectMachine

This is a helper function that refines the use of detect. This simplifies detecting a machine on the call and is the inverse of detectHuman.

Deprecated since: v2.2 - Use detectAnsweringMachine instead.

Parameters

ParameterTypeRequiredDescription
paramsobjectrequiredObject to tune the detector with the following properties:
timeoutnumberoptionalNumber of seconds to run the detector. Defaults to 30.0.
wait_for_beepbooleanoptionalWhether to wait until the AM is ready for voicemail delivery. Defaults to false.
initial_timeoutnumberoptionalNumber of seconds to wait for initial voice before giving up. Defaults to 4.5.
end_silence_timeoutnumberoptionalNumber of seconds to wait for voice to finish. Defaults to 1.0.
machine_voice_thresholdnumberoptionalHow many seconds of voice to decide is a machine. Defaults to 1.25.
machine_words_thresholdnumberoptionalHow many words to count to decide is a machine. Defaults to 6.

Returns

Promise<Relay.Calling.DetectResult> - Promise object that will be fulfilled with a Relay.Calling.DetectResult object.

Examples

Detect a machine on the current call.

// within an async function ..
const detectResult = await call.detectMachine()
if (detectResult.successful) {
// A machine has been detected!
}

detectMachineAsync

Asynchronous version of detectMachine. It does not wait the detector ends but returns a Relay.Calling.DetectAction you can interact with.

Deprecated since: v2.2 - Use detectAnsweringMachineAsync instead.

Parameters

See detectMachine for the parameter list.

Returns

Promise<Relay.Calling.DetectAction> - Promise object that will be fulfilled with a Relay.Calling.DetectAction object.

Examples

Detect a machine on the current call. Stop the action after 5 seconds.

async function main() {
const detectAction = await call.detectMachineAsync()

setTimeout(async () => {
await detectAction.stop()
}, 5000)
}

main().catch(console.error)

on

Attach an event handler for the event.

Parameters

ParameterTypeRequiredDescription
eventstringrequiredEvent name. See Events for the full list
handlerfunctionrequiredFunction to call when the event comes.

Returns

Relay.Calling.Call - The call object itself.

Examples

Subscribe to the answered and ended events for a given call.

call.on('answered', (call) => {
// Call has been answered from the remote party!
}).on('ended', (call) => {
// Call has ended.. cleanup something?
})

off

Remove an event handler that were attached with .on(). If you don't pass a handler, all listeners for that event will be removed.

Parameters

ParameterTypeRequiredDescription
eventstringrequiredEvent name. See Events for the full list
handlerfunctionoptionalFunction to remove. Note: handler will be removed from the stack by reference so make sure to use the same reference in both .on() and .off() methods.

Returns

Relay.Calling.Call - The call object itself.

Examples

Subscribe to the call ended state change and then, remove the event handler.

const callEndedHandler = (call) => {
// Call has ended.
})

call.on('ended', callEndedHandler)

// .. later
call.off('ended', callEndedHandler)

pass

This will allow a consumer to decline incoming calls without ending the call and redirect the call to another RELAY consumer.

Parameters

None

Returns

Promise<Relay.Calling.PassResult> - Promise object that will be fulfilled with a Relay.Calling.PassResult object.

Examples

Pass the inbound call.

import { RelayConsumer } from '@signalwire/node'

const consumer = new RelayConsumer({
project: process.env.PROJECT,
token: process.env.TOKEN,
contexts: ['home', 'office'],
onIncomingCall: async (call) => {
console.log('Inbound call', call.id, call.from, call.to)

// Pass call to another consumer
const passResult = await call.pass()
if (!passResult.successful) {
console.error('Error passing the call')
return
}

console.log('Call passed to another consumer!')
}
})

consumer.run()

record

Start recording the call and waits until the recording ends or fails.

Parameters

ParameterTypeRequiredDescription
paramsobjectoptionalObject with the following properties:
beepbooleanoptionalDefault to false.
stereobooleanoptionalDefault to false.
formatstringoptionalmp3 or wav. Default mp3.
directionstringoptionallisten, speak or both. Default to speak.
initial_timeoutnumberoptionalHow long to wait in seconds until something is heard in the recording. Disable with 0. Default 5.0.
end_silence_timeoutnumberoptionalHow long to wait in seconds until caller has stopped speaking. Disable with 0. Default 1.0.
terminatorsstringoptionalDTMF digits that will end the recording. Default #*.

Returns

Promise<Relay.Calling.RecordResult> - Promise object that will be fulfilled with a Relay.Calling.RecordResult object.

Examples

Start recording audio in the call for both direction in stereo mode, if successful, grab url, duration and size from the RecordResult object.

async function main() {
const params = {
stereo: true,
direction: 'both'
}
const recordResult = await call.record(params)

if (recordResult.successful) {
const { url, duration, size } = recordResult
}
}

main().catch(console.error)

recordAsync

Asynchronous version of record. It does not wait the end of recording but returns a Relay.Calling.RecordAction you can interact with.

Parameters

See record for the parameter list.

Returns

Promise<Relay.Calling.RecordAction> - Promise object that will be fulfilled with a Relay.Calling.RecordAction object.

Examples

Start recording audio in the call for both direction in stereo mode and stop it after 5 seconds.

async function main() {
const params = {
stereo: true,
direction: 'both'
}
const recordAction = await call.recordAsync(params)

setTimeout(async () => {
await recordAction.stop()
}, 5000)
}

main().catch(console.error)

refer

Transfer a SIP call to an external SIP endpoint.

Parameters

ParameterTypeRequiredDescription
paramsobjectrequiredObject with the following properties:
tostringrequiredSIP URI to transfer the call to.
headers{name: string, value: string}[]optionalArray of headers. Must be X-headers only.

Returns

Promise<Relay.Calling.ReferResult> - Promise object that will be fulfilled with a Relay.Calling.ReferResult object.

Examples

Transfer the call to another SIP endpoint.

async function main() {
const params = {
to: 'sip:user@sip.example.com',
}
const referResult = await call.refer(params)

if (referResult.successful) {
const { referTo, referNotifyCode, referResponseCode } = referResult
}
}

main().catch(console.error)

referAsync

Asynchronous version of refer. It does not wait the end of the REFER but returns a Relay.Calling.ReferAction you can interact with.

Parameters

See refer for the parameter list.

Returns

Promise<Relay.Calling.ReferAction> - Promise object that will be fulfilled with a Relay.Calling.ReferAction object.

Examples

Async transfer the call to another SIP endpoint.

async function main() {
const params = {
to: 'sip:user@sip.example.com',
}

call.on('refer.success', (params) => {
// listen for the success event
console.log('Refer success', params)
})

const referAction = await call.referAsync(params)
}

main().catch(console.error)

sendDigits

This method sends DTMF digits to the other party on the call.

Parameters

ParameterTypeRequiredDescription
digitsstringrequiredString of DTMF digits to send. Allowed digits are 1234567890*#ABCD and wW for short and long waits. If any invalid characters are present, the entire operation is rejected.

Returns

Promise<Relay.Calling.SendDigitsResult> - Promise object that will be fulfilled with a Relay.Calling.SendDigitsResult object.

Examples

Send some digits.

async function main() {
const result = await call.sendDigits('123')
}

main().catch(console.error)

sendDigitsAsync

Asynchronous version of sendDigits. It does not wait for the sending event to complete, and immediately returns a Relay.Calling.SendDigitsAction object you can interact with.

Parameters

See sendDigits for the parameter list.

Returns

Promise<Relay.Calling.SendDigitsAction> - Promise object that will be fulfilled with a Relay.Calling.SendDigitsAction object.

Examples

Send some digits and then check if the operation is completed using the SendDigitsAction object.

async function main() {
const action = await call.sendDigitsAsync('123')

setTimeout(() => {
if (action.completed) {
// ...
}
}, 1000)
}

main().catch(console.error)

tap

Intercept call media and stream it to the specify endpoint. It waits until the end of the call.

Parameters

ParameterTypeRequiredDescription
paramsobjectrequiredObject with the following properties:
audio_directionstringrequiredlisten what the caller hears, speak what the caller says or both.
target_typestringrequiredProtocol to use: rtp or ws, defaults to rtp.
target_ptimenumberoptionalPacketization time in ms. It will be the same as the tapped media if not set.
codecstringoptionalCodec to use. It will be the same as the tapped media if not set.
  • To tap through RTP:
ParameterTypeRequiredDescription
target_addrstringrequiredRTP IP v4 address.
target_portnumberrequiredRTP port.

Returns

Promise<Relay.Calling.TapResult> - Promise object that will be fulfilled with a Relay.Calling.TapResult object.

Examples

Tapping audio from the call, if successful, print both source and destination devices from the TapResult object.

// within an async function ..
const params = {
audio_direction: 'both',
target_type: 'rtp',
target_addr: '192.168.1.1',
target_port: 1234
}
const tapResult = await call.tap(params)
if (tapResult.successful) {
const { sourceDevice, destinationDevice } = tapResult
console.log(sourceDevice)
console.log(destinationDevice)
}

tapAsync

Asynchronous version of tap. It does not wait the end of tapping but returns a Relay.Calling.TapAction you can interact with.

Parameters

See tap for the parameter list.

Returns

Promise<Relay.Calling.TapAction> - Promise object that will be fulfilled with a Relay.Calling.TapAction object.

Examples

Tapping audio from the call and then stop it using the TapAction object.

// within an async function ..
const params = {
audio_direction: 'both',
target_type: 'rtp',
target_addr: '192.168.1.1',
target_port: 1234
}
const tapAction = await call.tapAsync(params)
// Do other things while tapping the media and then stop it..
setTimeout(async () => {
await tapAction.stop()
}, 5000)

promptRingtone

This is a helper function that refines the use of prompt. This function simplifies playing ringtones while collecting user's input from the call, such as digits and speech.

Parameters

You can set all the properties that prompt accepts replacing media with:

ParameterTypeRequiredDescription
namestringrequiredThe name of the ringtone. See Ringtones for the supported values.
durationnumberoptionalDuration of ringtone to play. Default to 1 ringtone iteration.

The SDK will build the media for you.

Returns

Promise<Relay.Calling.PromptResult> - Promise object that will be fulfilled with a Relay.Calling.PromptResult object.

Examples

Play US ringtone for 30 seconds while collect digits.

async function main() {
const params = {
type: 'digits',
digits_max: 3,
name: 'us',
duration: 30
}
const promptResult = await call.promptRingtone(params)
if (promptResult.successful) {
const type = promptResult.type // digit
const pin = promptResult.result // pin entered by the user
}
}

main().catch(console.error)

promptRingtoneAsync

Asynchronous version of promptRingtone. It does not wait the collection to completes but returns a Relay.Calling.PromptAction you can interact with.

Parameters

See promptRingtone for the parameter list.

Returns

Promise<Relay.Calling.PromptAction> - Promise object that will be fulfilled with a Relay.Calling.PromptAction object.

Examples

Play US ringtone for 30 seconds while collect digits in asynchronous.

async function main() {
const params = {
type: 'digits',
digits_max: 3,
name: 'us',
duration: 30
}
const promptAction = await call.promptRingtoneAsync(params)
// .. do other important things while collecting user digits..

if (promptAction.completed) {
const result = promptAction.result // => PromptResult object
}
}

main().catch(console.error)

waitFor

Wait for specific events on the Call or returns false if the Call ends without getting them.

Parameters

ParameterTypeRequiredDescription
event1, event2, ..eventNstring or string[]requiredOne or more Call state events. See Events for the full list

Returns

Promise<boolean> - Promise resolved with true or false.

Examples

Wait for ending or ended events.

// within an async function ..
const success = await call.waitFor('ending', 'ended')
if (success) {
// ...
}

waitForAnswered

This is a helper function that refines the use of waitFor. This simplifies waiting for the answered state.

Parameters

None

Returns

Promise<boolean> - Promise resolved with true or false.

Examples

Wait for the answered event.

// within an async function ..
const success = await call.waitForAnswered()
if (success) {
// ...
}

waitForEnded

This is a helper function that refines the use of waitFor. This simplifies waiting for the ended state.

Parameters

None

Returns

Promise<boolean> - Promise resolved with true or false.

Examples

Wait for the ended event.

// within an async function ..
const success = await call.waitForEnded()
if (success) {
// ...
}

waitForEnding

This is a helper function that refines the use of waitFor. This simplifies waiting for the ending state.

Parameters

None

Returns

Promise<boolean> - Promise resolved with true or false.

Examples

Wait for the ending event.

// within an async function ..
const success = await call.waitForEnding()
if (success) {
// ...
}

waitForRinging

This is a helper function that refines the use of waitFor. This simplifies waiting for the ringing state.

Parameters

None

Returns

Promise<boolean> - Promise resolved with true or false.

Examples

Wait for the ringing event.

// within an async function ..
const success = await call.waitForRinging()
if (success) {
// ...
}

Events

All these events can be used to track the calls lifecycle and instruct SignalWire on what to do for each different state.

State Events

To track the state of a call.

EventDescription
stateChangeEvent dispatched when Call state changes.
createdThe call has been created in Relay.
ringingThe call is ringing and has not yet been answered.
answeredThe call has been picked up.
endingThe call is hanging up.
endedThe call has ended.

Connect Events

To track the connect state of a call.

EventDescription
connect.stateChangeEvent dispatched when the Call connect state changes.
connect.connectingCurrently calling the phone number(s) to connect.
connect.connectedThe calls are being connected together.
connect.failedThe last call connection attempt failed.
connect.disconnectedThe call was either never connected or the last call connection completed.

Play Events

To track a playback state.

EventDescription
play.stateChangeEvent dispatched when the state of a playing changes.
play.playingA playback in playing on the call.
play.errorA playback failed to start.
play.finishedThe playback has ended.

Record Events

To track a recording state.

EventDescription
record.stateChangeEvent dispatched when the state of a recording changes.
record.recordingThe call is being recorded.
record.no_inputThe recording failed due to no input.
record.finishedThe recording has ended.

Refer Events

To track a REFER state.

EventDescription
refer.stateChangeEvent dispatched when the state of a refer process changes.
refer.inProgressThe transfer is in progress.
refer.cancelThe transfer has been cancelled.
refer.busyThe SIP endpoint is busy.
refer.noAnswerThe SIP endpoint did not answer.
refer.errorThe refer attempt failed.
refer.successThe refer attempt succeeded.

Prompt Events

To track a prompt state.

EventDescription
promptThe prompt action on the call has ended.

Fax Events

To track a fax state.

EventDescription
fax.errorFaxing failed.
fax.finishedFaxing has finished.
fax.pageA fax page has been sent or received.

Detect Events

To track a detector state.

EventDescription
detect.errorThe detector has failed.
detect.finishedThe detector has finished.
detect.updateThere is a notification from the detector (eg: a new DTMF).

Tap Events

To track a tapping state.

EventDescription
tap.tappingThe tap action has started on the call.
tap.finishedTap has finished.

Digits Events

To track a send digits action state.

EventDescription
sendDigits.finishedDigits have been sent.

Ringtones

Here you can find all the accepted values for the ringtone to play, based on short country codes:

PropertyCountry Code
nameat, au, bg, br, be, ch, cl, cn, cz, de, dk, ee, es, fi, fr, gr, hu, il, in, it, lt, jp, mx, my, nl, no, nz, ph, pl, pt, ru, se, sg, th, uk, us, tw, ve, za