Navbar
Logo icon Name

Relay SDK for Node.js

Getting Started

The Relay SDK for Node.js enables Node.js developers to connect and use SignalWire's Relay APIs within their own Node.js code. Our Relay SDK allows developers to build or add robust and innovative communication services to their applications.

The Relay SDK for Node.js is easy to use and only takes a few minute to setup and get running.

Latest Version:

Source Code: signalwire/signalwire-node

Support: SignalWire Community Slack Channel

Installation

Install the package using NPM:

npm install @signalwire/node

In order to use the Node.js client, you must get your host, project, and token from your SignalWire dashboard.

For more information on finding your access token, visit Relay Access Keys & Tokens

const { RelayClient } = require('@signalwire/node')
const client = new RelayClient({
  host: 'example.signalwire.com',
  project: 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX',
  token: 'PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
})

You can then use client to make requests.

Using the SDK

The Node.js SDK can be used to get up and running quickly. Below is an example of setting up a connection to Relay and making an outbound call.

const { RelayClient } = require('@signalwire/node')
const client = new RelayClient({
  host: 'example.signalwire.com',
  project: 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX',
  token: 'PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
})

client.on('signalwire.ready', async (client) => {

  const call = await client.calling.newCall({
    type: 'phone',
    from: '+1XXXXXXXXXX',
    to: '+1YYYYYYYYYY',
    timeout: 30
  })

  call.on('answered', (call) => {
    // Call has been picked up!
  })

  call.begin()
})

client.connect()

Read further for all the features and endpoints available on SignalWire's Relay API.

API Reference

Relay.Client

Relay.Client is the basic connection to Relay, allowing you send commands to Relay and setup handlers for inbound events.

Constructor

Constructs a client object to interact with Relay.

Parameters

host string required The endpoint URI to send requests to. The SignalWire Space URL, should be a string similar to: {your-space}.signalwire.com.
project string required Project Key from your SignalWire Space
token string required Token from your SignalWire Space

Examples

Create a Client to interact with the Relay API.

const client = new RelayClient({
  host: 'my-space.signalwire.com',
  project: 'my-project-id',
  token: 'my-project-token'
})

Properties

connected boolean Returns true if the client has connected to Relay.
calling Relay.Calling Returns a Relay.Calling instance associated with the client.

Methods

connect()

Activates the connection to the Relay API. The connection to Relay does not happen automatically so that you can setup handlers to events that might occur before the connection is successfully established.

Available In:

Returns

Promise<void>

Examples

// Make sure you have attached the listeners you need before connecting the client, or you might miss some events.
await client.connect()

disconnect()

Disconnect the client from Relay.

Available In:

Returns

void

Examples

client.disconnect()

on('event', handler)

Attach an event handler for a specific type of event.

Available In:

Parameters

event string required Event name. Full list of events Relay.Client Events
handler function required Function to call when the event comes.

Returns

Relay.Client - The client object itself.

Examples

Subscribe to the signalwire.ready and signalwire.error events.

client.on('signalwire.ready', (client) => {
  // Your client is ready!
}).on('signalwire.error', (error) => {
  // Got an error...
})

off('event', handler)

Remove an event handler that were attached with .on(). If no handler parameter is passed, all listeners for that event will be removed.

Parameters

event string required Event name. Full list of events Relay.Client Events
handler function optional Function 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.Client - The client object itself.

Examples

Subscribe to the signalwire.error and then, remove the event handler.

const errorHandler = (error) => {
  // Log the error..
}

client.on('signalwire.error', errorHandler)

// .. later
client.off('signalwire.error', errorHandler)

Events

All available events you can attach a listener on.

signalwire.ready The session has been established and all other methods can now be used.
signalwire.error There is an error dispatch at the session level.
signalwire.socket.open The websocket is open. However, you have not yet been authenticated.
signalwire.socket.error The websocket gave an error.
signalwire.socket.message The client has received a message from the websocket.
signalwire.socket.close The websocket is closing.

Relay.Calling

This represents the API interface for the Calling Relay Service. This object is used to make requests related to managing end to end calls.

Methods

newCall({ type, from, to, timeout })

Create a new Call object. The call has not started yet allowing you to attach event listeners on it.

Available In:

Parameters

type string required The type of call. Only phone is currently supported.
from string required The party the call is coming from.
Must be a SignalWire number or SIP endpoint that you own.
to string required The party you are attempting to call.
timeout number optional The time, in seconds, the call will ring before going to voicemail.

Returns

Promise<Call> - Promise that will be fulfilled with the new Call object.

Examples

Create a Call object with async/await syntax.

async function main() {
  const call = await client.calling.newCall({
    type: 'phone',
    from: '+1XXXXXXXXXX',
    to: '+1YYYYYYYYYY',
    timeout: 30
  })
  // Use the call object..
}

main().catch(console.error)

onInbound('context', handler)

Attach an event handler that will be called with inbound calls on the specified context.

Available In:

Parameters

context string required The context you want to listen on. You can create and manage these contexts, such as "pbx", "office" or "work" from your SignalWire Space.
handler function required Function that instructs SignalWire on what to do when receiving an inbound call from the specified context.

Returns

Promise<void>

Examples

Listen for inbound calls on office context.

async function main() {
  const handleOfficeCalls = (call) => {
    console.log('Got an inbound call in the "office" context', call)
    // Use the call object..
  }

  await client.calling.onInbound('office', handleOfficeCalls)
}

main().catch(console.error)

Relay.Calling.Call

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

Properties

id string The unique identifier of the call.
type string The type of call. Only phone is currently supported.
from string The phone number that the call is coming from.
to string The phone number you are attempting to call.
timeout number The seconds the call rings before being transferred to voicemail.
state string The current state of the call. See Relay.Calling.Call State Events for all the possible call states.
prevState string The previous state of the call.
connectState string The current state of the call connection. See Relay.Calling.Call Connect Events for all the possible connection states.
prevConnectState string The previous state of the call connection.
context string The context the call belongs to.
peer Relay.Calling.Call The call your original call is connected to.
recordings array Array of recordings on the calls.
playbacks array Array of playbacks on the calls.

Methods

on('event', handler)

Attach an event handler for the event.

Available In:

Parameters

event string required Event name. Full list of events Relay.Calling.Call Events
handler function required Function 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('event', handler)

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

Available In:

Parameters

event string required Event name. Full list of events Relay.Calling.Call Events
handler function optional Function 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)

begin()

This will start a call that was created with the newCall() method.

Available In:

Parameters

None

Returns

Promise - Resolved or Rejected with the Relay response.

Examples

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

  await call.begin()
}

main().catch(console.error)

hangup()

Hangup the call.

Available In:

Parameters

None

Returns

Promise - Resolved or Rejected with the Relay response.

Examples

Hangup inbound calls in the pbx context if the Agent is not available.

async function main() {
  const handler = async (call) => {
    if (Agent.isAvailable() === false) {
      await call.hangup().catch(console.error)
    }
  }

  await client.calling.onInbound('pbx', handler)
}

main().catch(console.error)

answer()

Answer an inbound call.

Available In:

Parameters

None

Returns

Promise - Resolved or Rejected with the Relay response.

Examples

Answer inbound calls in the office context.

async function main() {
  const handler = async (call) => {
    await call.answer().catch(console.error)
  }

  await client.calling.onInbound('office', handler)
}

main().catch(console.error)

connect(device [, device2, ..., deviceN])

Attempt to connect an existing call to a new outbound call. 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.

Available In:

Parameters

device ... deviceN Device or Device[] required A single, a list or an array of Device. Nested depends on whether to dial in serial or parallel.

Returns

Promise - Resolved or Rejected with the Relay response.

Examples

PRO TIP: In the examples below we attach listeners on connect.connected and connect.failed to be notified about those events!

 

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

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

  call.on('connect.connected', (call) => {
    // Your call has been connected to the first one that answered
  })
  .on('connect.failed', (call) => {
    // Your call failed to connect
  })
  .on('answered', async (call) => {
    const result = await call.connect(
      { type: 'phone', to: '+18991114444', timeout: 30 },
      { type: 'phone', to: '+18991114445', timeout: 20 }
    ).catch(console.error)
  })

  await call.begin()
}

main().catch(console.error)

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.

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

  call.on('connect.connected', (call) => {
    // Your call has been connected to the first one that answered
  })
  .on('connect.failed', (call) => {
    // Your call failed to connect
  })
  .on('answered', async (call) => {
    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 }
      ]
    ).catch(console.error)
  })

  await call.begin()
}

main().catch(console.error)

playMedia(media [, media2, ..., mediaN])

Play one or multiple media in a call.

Available In:

Parameters

media ... mediaN object required One or more objects with the following structure:
type string required audio, tts or silence
params.url string required Http(s) URL to audio resource to play.
params.text string required TTS to play.
params.language string optional Default to en-US.
params.gender string optional male or female. Default to female.
params.duration number required Seconds of silence to play.

Returns

Promise - Resolved with a Relay.Calling.PlayMediaAction or Rejected with the Relay error.

Examples

Play an Mp3 file.

async function main() {
  const action = await call.playMedia({ type: 'audio', params: { url: 'https://example.domain.com/audio.mp3' } })
  // Use action to interact with the media..
}

main().catch(console.error)

Play Text-to-Speech.

async function main() {
  const action = await call.playMedia({ type: 'tts', params: { text: 'Welcome at SignalWire!' } }
  // Use action to interact with the media..
}

main().catch(console.error)

Play 5 seconds of silence.

async function main() {
  const action = await call.playMedia({ type: 'silence', params: { duration: 5 } })
  // Use action to interact with the media..
}

main().catch(console.error)

Play multiple media elements in the call.

async function main() {
  const media = [
    { type: 'silence', params: { duration: 2 } },
    { type: 'tts', params: { text: 'Listen this awesome file!' } },
    { type: 'audio', params: { url: 'https://example.domain.com/audio.mp3' } },
    { type: 'silence', params: { duration: 5 } },
    { type: 'tts', params: { text: 'Did you like it?' } }
  ]
  const action = await call.playMedia(...media)
  // Use action to interact with the media..
}

main().catch(console.error)

playAudio('url')

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

Available In:

Parameters

url string required Http(s) URL to audio resource to play.

Returns

Promise - Resolved with a Relay.Calling.PlayAudioAction or Rejected with the Relay error.

Examples

Play an Mp3 file.

async function main() {
  const action = await call.playAudio('https://example.domain.com/audio.mp3')
  // Use action to interact with the media..
}

main().catch(console.error)

playTTS({ text, language, gender })

This is a helper function that refines the use of playMedia(). This simplifies playing TTS.

Available In:

Parameters

text string required TTS to play.
language string optional Default to en-US.
gender string optional male or female. Default to female.

Returns

Promise - Resolved with a Relay.Calling.PlayTTSAction or Rejected with the Relay error.

Examples

Play TTS.

async function main() {
  const action = await call.playTTS({ text: 'Welcome at SignalWire!', gender: 'male' })
  // Use action to interact with the media..
}

main().catch(console.error)

playSilence(duration)

This is a helper function that refines the use of playMedia(). This simplifies playing silence.

Available In:

Parameters

duration number required Seconds of silence to play.

Returns

Promise - Resolved with a Relay.Calling.PlaySilenceAction or Rejected with the Relay error.

Examples

Play silence for 5 seconds.

async function main() {
  const action = await call.playSilence(5)
  // Use action to interact with the media..
}

main().catch(console.error)

playMediaAndCollect(collect, media [, media2, ..., mediaN])

Play one or multiple media while collecting user's input from the call at the same time, such as digits and speech.

Available In:

Parameters

collect object required Object with initial_timeout, digits and speech properties.
collect.initial_timeout number required Timeout in seconds.
collect.digits object Optional if collect.speech is set.
collect.digits.max number required Max digits to collect.
collect.digits.digit_timeout number required Timeout in seconds between each digit.
collect.digits.terminators string optional DTMF digits that will end the recording.
Default not set.
collect.speech object Optional if collect.digits is set.
collect.speech.end_silence_timeout number optional How much silence to wait for end of speech.
Default 1 second.
collect.speech.language string optional Language to detect.
Default to en-US.
collect.speech.hints array optional Array of expected phrases to detect.
media ... mediaN object required One or more Media objects with the same structure used in .playMedia()

Returns

Promise - Resolved with a Relay.Calling.PlayMediaAndCollectAction or Rejected with the Relay error.

Examples

Attach a listener for the collect event and start collecting digits while playing TTS.

async function main() {
  call.on('collect', (call, result) => {
    console.log('Collect result:', result)
  })

  const collect = { initial_timeout: 10, digits: { max: 3, digit_timeout: 5 } }
  const tts = { type: 'tts', params: { text: "Please, digit something.." } }
  const action = await call.playMediaAndCollect(collect, tts)
  // Use action to interact with the collect..
}

main().catch(console.error)

playAudioAndCollect(collect, 'url')

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

Available In:

Parameters

collect object required See the parameters of playMediaAndCollect() for all the properties.
url string required Http(s) URL to audio resource to play.

Returns

Promise - Resolved with a Relay.Calling.PlayAudioAndCollectAction or Rejected with the Relay error.

Examples

Collect digits while playing an Mp3 file.

async function main() {
  call.on('collect', (call, result) => {
    console.log('Collect result:', result)
  })

  const collect = { initial_timeout: 10, digits: { max: 3, digit_timeout: 5 } }
  const action = await call.playAudioAndCollect(collect, 'https://example.domain.com/audio.mp3')
  // Use action to interact with the collect..
}

main().catch(console.error)

playTTSAndCollect(collect, { text, language, gender })

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

Available In:

Parameters

collect object required See the parameters of playMediaAndCollect() for all the properties.
params object required Object with the following properties:
params.text string required TTS to play.
params.language string optional Default to en-US.
params.gender string optional male or female. Default to female.

Returns

Promise - Resolved with a Relay.Calling.PlayTTSAndCollectAction or Rejected with the Relay error.

Examples

Collect digits while playing TTS.

async function main() {
  call.on('collect', (call, result) => {
    console.log('Collect result:', result)
  })

  const collect = { initial_timeout: 10, digits: { max: 3, digit_timeout: 5 } }
  const action = await call.playTTSAndCollect(collect, { text: 'Welcome at SignalWire!', gender: 'male' })
  // Use action to interact with the collect..
}

main().catch(console.error)

playSilenceAndCollect(collect, duration)

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

Available In:

Parameters

collect object required See the parameters of playMediaAndCollect() for all the properties.
duration number required Seconds of silence to play.

Returns

Promise - Resolved with a Relay.Calling.PlaySilenceAndCollectAction or Rejected with the Relay error.

Examples

Collect digits while playing 5 seconds of silence.

async function main() {
  call.on('collect', (call, result) => {
    console.log('Collect result:', result)
  })

  const collect = { initial_timeout: 10, digits: { max: 3, digit_timeout: 5 } }
  const action = await call.playSilenceAndCollect(collect, 5)
  // Use action to interact with the collect..
}

main().catch(console.error)

record({ audio })

Start recording the call.

Available In:

Parameters

params object optional Object with the following properties:
params.audio object optional How record the audio in the call:
params.audio.beep boolean optional Default to false.
params.audio.stereo boolean optional Default to false.
params.audio.format string optional Mp3 or WAV. Default to mp3.
params.audio.direction string optional listen / speak / both. Default to speak.
params.audio.initial_timeout number optional How long to wait in seconds until something is heard in the recording. Disable with 0.
Default 5.0.
params.audio.end_silence_timeout number optional How long to wait in seconds until caller has stopped speaking. Disable with 0.
Default 1.0.
params.audio.terminators string optional DTMF digits that will end the recording.
Default #*.

Returns

Promise - Resolved with a Relay.Calling.RecordAction or Rejected with the Relay error.

Examples

PRO TIP: In the example below we attach a listener on record.finished event to be notified when the recording is over!

 

Start recording audio in the call for both direction in stereo mode.

async function main() {
  call.on('record.finished', (call, result) => {
    console.log('Recording result:', result)
  })

  const action = await call.record({
    audio: {
      stereo: true,
      direction: 'both'
    }
  })
  // Use action to interact with the recording..
}

main().catch(console.error)

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.

created The call has been created in Relay.
ringing The call is ringing and has not yet been answered.
answered The call has been picked up.
ending The call is hanging up.
ended The call has ended.

Connect Events

To track the connect state of a call.

connect.connecting Currently calling the phone number(s) to connect.
connect.connected The calls are being connected together.
connect.failed The last call connection attempt failed.
connect.disconnected The call was either never connected or the last call connection completed.

Play Events

To track a playback state.

play.playing A playback in playing on the call.
play.error A playback failed to start.
play.finished The playback has ended.

Record Events

To track a recording state.

record.recording The call is being recorded.
record.no_input The recording failed due to no input.
record.finished The recording has ended.

Collect Events

To track a collect state.

collect The collect action on the call has ended.

Relay.Calling.RecordAction

This object represents a recording action that is currently active on a call.

Properties

call Relay.Calling.Call This is the call the action is occurring on.

Methods

stop()

Stop the action immediately.

Available In:

Parameters

None

Returns

Promise - Resolved or Rejected with the Relay response.

Examples

Start recording in stereo mode and stop it if Agent is not available.

async function main() {
  const action = await call.record({
    audio: {
      stereo: true
    }
  })

  if (Agent.isAvailable() === false) {
    await action.stop()
  }
}

main().catch(console.error)

Relay.Calling.PlayMediaAction

This object represents a media action that is currently active on a call.

Properties

call Relay.Calling.Call This is the call the action is occurring on.

Methods

stop()

Stop the action immediately.

Available In:

Parameters

None

Returns

Promise - Resolved or Rejected with the Relay response.

Examples

Play multiple media elements in the call and stop them all if Agent is not available.

async function main() {
  const media = [
    { type: 'tts', params: { text: 'Listen this awesome file!' } },
    { type: 'audio', params: { url: 'https://example.domain.com/audio.mp3' } },
    { type: 'silence', params: { duration: 5 } },
    { type: 'tts', params: { text: 'Did you like it?' } }
  ]
  const action = await call.playMedia(...media)
  if (Agent.isAvailable() === false) {
    await action.stop()
  }
}

main().catch(console.error)

Relay.Calling.PlayAudioAction

This object represents an audio action that is currently active on a call.

Properties

call Relay.Calling.Call This is the call the action is occurring on.

Methods

stop()

Stop the action immediately.

Available In:

Parameters

None

Returns

Promise - Resolved or Rejected with the Relay response.

Examples

Play an Mp3 file and stop it if Agent is not available.

async function main() {
  const action = await call.playAudio('https://example.domain.com/audio.mp3')
  if (Agent.isAvailable() === false) {
    await action.stop()
  }
}

main().catch(console.error)

Relay.Calling.PlayTTSAction

This object represents an TTS action that is currently active on a call.

Properties

call Relay.Calling.Call This is the call the action is occurring on.

Methods

stop()

Stop the action immediately.

Available In:

Parameters

None

Returns

Promise - Resolved or Rejected with the Relay response.

Examples

Play TTS in the call and stop it if Agent is not available.

async function main() {
  const action = await call.playTTS({ text: 'Welcome at SignalWire!', gender: 'male' })
  if (Agent.isAvailable() === false) {
    await action.stop()
  }
}

main().catch(console.error)

Relay.Calling.PlaySilenceAction

This object represents an silence action that is currently active on a call.

Properties

call Relay.Calling.Call This is the call the action is occurring on.

Methods

stop()

Stop the action immediately.

Available In:

Parameters

None

Returns

Promise - Resolved or Rejected with the Relay response.

Examples

Play 10 seconds of silence and stop it if Agent is available.

async function main() {
  const action = await call.playSilence(10)
  if (Agent.isAvailable()) {
    await action.stop()
  }
}

main().catch(console.error)

Relay.Calling.PlayMediaAndCollectAction

This object represents a media & collect action that is currently active on a call.

Properties

call Relay.Calling.Call This is the call the action is occurring on.

Methods

stop()

Stop the action immediately.

Available In:

Parameters

None

Returns

Promise - Resolved or Rejected with the Relay response.

Examples

Collecting digits while playing multiple media elements in the call and stop them all if Agent is not available.

async function main() {
  const collect = { initial_timeout: 10, digits: { max: 3, digit_timeout: 5 } }
  const media = [
    { type: 'tts', params: { text: 'Listen this awesome file!' } },
    { type: 'audio', params: { url: 'https://example.domain.com/audio.mp3' } },
    { type: 'silence', params: { duration: 5 } },
    { type: 'tts', params: { text: 'Did you like it?' } }
  ]
  const action = await call.playMediaAndCollect(collect, ...media)
  if (Agent.isAvailable() === false) {
    await action.stop()
  }
}

main().catch(console.error)

Relay.Calling.PlayAudioAndCollectAction

This object represents an audio & collect action that is currently active on a call.

Properties

call Relay.Calling.Call This is the call the action is occurring on.

Methods

stop()

Stop the action immediately.

Available In:

Parameters

None

Returns

Promise - Resolved or Rejected with the Relay response.

Examples

Play an Mp3 file and stop it if Agent is not available.

async function main() {
  const collect = { initial_timeout: 10, digits: { max: 3, digit_timeout: 5 } }
  const action = await call.playAudioAndCollect(collect, 'https://example.domain.com/audio.mp3')
  if (Agent.isAvailable() === false) {
    await action.stop()
  }
}

main().catch(console.error)

Relay.Calling.PlayTTSAndCollectAction

This object represents a TTS & collect action that is currently active on a call.

Properties

call Relay.Calling.Call This is the call the action is occurring on.

Methods

stop()

Stop the action immediately.

Available In:

Parameters

None

Returns

Promise - Resolved or Rejected with the Relay response.

Examples

Collecting digits while playing TTS in the call and stop it if Agent is not available.

async function main() {
  const collect = { initial_timeout: 10, digits: { max: 3, digit_timeout: 5 } }
  const ttsParams = { text: 'Welcome at SignalWire!', gender: 'male' }
  const action = await call.playTTSAndCollect(collect, ttsParams)
  if (Agent.isAvailable() === false) {
    await action.stop()
  }
}

main().catch(console.error)

Relay.Calling.PlaySilenceAndCollectAction

This object represents a silence & collect action that is currently active on a call.

Properties

call Relay.Calling.Call This is the call the action is occurring on.

Methods

stop()

Stop the action immediately.

Available In:

Parameters

None

Returns

Promise - Resolved or Rejected with the Relay response.

Examples

Collecting digits while playing 10 seconds of silence and stop it if Agent is available.

async function main() {
  const collect = { initial_timeout: 10, digits: { max: 3, digit_timeout: 5 } }
  const action = await call.playSilenceAndCollect(collect, 10)
  if (Agent.isAvailable()) {
    await action.stop()
  }
}

main().catch(console.error)

Examples

Follow the examples to see how's easy to use the Relay SDK to interact with inbound or outbound calls.

Inbound Calls

Receive inbound calls from the office context, answer them and play an Mp3 audio. Write a console.log when the play state change.

const { RelayClient } = require('@signalwire/node')
const CONTEXT = 'office'
const AUDIO_URL = 'https://cdn.signalwire.com/default-music/welcome.mp3'

const client = new RelayClient({
  host: 'example.signalwire.com',
  project: 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX',
  token: 'PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
})

client.on('signalwire.error', (error) => {
  console.error('SignalWire Error: ', error)
})

client.on('signalwire.ready', async (client) => {
  try {
    await client.calling.onInbound(CONTEXT, handleInboundCall)
    console.log(`\n You are listening for inbound calls from '${CONTEXT}' context.. \n`)
  } catch (error) {
    console.error('Inbound call error: ', error)
  }
})

async function handleInboundCall(call) {
  console.log(`New inbound call in context: "${call.context}"`)
  try {
    call.on('play.stateChange', (call, params) => {
      console.log(`CallId: ${call.id} - Play state changed to: "${params.state}"`)
    })
    call.on('answered', async (call) => {
      const action = await call.playAudio(AUDIO_URL).catch(console.error)
    })

    await call.answer()
  } catch (error) {
    console.error('Answering call error: ', error)
  }
}

client.connect().catch(console.error)

Outbound Calls

Make a call and, on answered, start collect user digits while playing TTS. When collect has completed, logs the result.

const { RelayClient } = require('@signalwire/node')

const client = new RelayClient({
  host: 'example.signalwire.com',
  project: 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX',
  token: 'PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
})

client.on('signalwire.error', (error) => {
  console.error('SignalWire Error: ', error)
})

client.on('signalwire.ready', async (client) => {
  try {
    await makeCall()
  } catch (error) {
    console.error('Outbound call error: ', error)
  }
})

async function makeCall() {
  const call = await client.calling.newCall({
    type: 'phone',
    from: '+1XXXXXXXXXX', // Must be a number in your SignalWire Space
    to: '+1YYYYYYYYYY'
  })

  call.on('answered', async (call) => {
    const collect = { initial_timeout: 10, digits: { max: 3, digit_timeout: 5 } }
    const ttsParams = { text: 'Welcome at SignalWire!', gender: 'male' }
    await call.playTTSAndCollect(collect, ttsParams).catch(console.error)
  })

  call.on('collect', (call, result) => {
    console.log(`Digits collected: `, result.params.digits)
  })

  await call.begin()
}

client.connect().catch(console.error)