Navbar
  • Guides
  • REST APIs
  • SDKs Reference
  • Compatibility API
  • Log In
  • Sign Up
  • Relay SDK for Node.js
  • API Reference
  • Examples
  • 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

    NOTE: This is an old version of the RELAY Node.js SDK. The RELAY Realtime SDK is the latest Node.js SDK version. While this SDK is still functional, you should consider upgrading to the newest version as this SDK moves closer to deprecation. For some pointers on migrating, please read our post "Upgrade Your RELAY Game".

    Installation

    Install the package using NPM:

    npm install @signalwire/node
    

    Minimum Requirements

    The Node.js SDK may be used with Node.js 8.0 or greater.

    Using the SDK

    The Node.js SDK can be used to get up and running with Relay quickly and easily. In order to use the Node.js client, you must get your project and token from your SignalWire dashboard.

    There are a few ways to get started, depending on your needs: Relay.Consumer, Relay.Task, and Relay.Client.

    Relay Consumer

    A Relay.Consumer creates a long running process, allowing you to respond to incoming requests and events in realtime. Relay Consumers abstract all the setup of connecting to Relay and automatically dispatches workers to handle requests; so you can concentrate on writing your code without having to worry about multi-threading or blocking, everything just works. Think of Relay Consumers like a background worker system for all your calling and messaging needs.

    Relay Consumers can scale easily, simply by running multiple instances of your Relay.Consumer process. Each event will only be delivered to a single consumer, so as your volume increases, just scale up! This process works well whether you are using Docker Swarm, a Procfile on Heroku, your own webserver, and most other environments.

    Setting up a new consumer is the easiest way to get up and running.

    const { RelayConsumer } = require('@signalwire/node')
    
    const consumer = new RelayConsumer({
      project: 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX',
      token: 'PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
      contexts: ['home', 'office'],
      ready: async ({ client }) => {
        // Consumer is successfully connected with Relay.
        // You can make calls or send messages here..
      },
      onIncomingCall: async (call) => {
        const { successful } = await call.answer()
        if (!successful) { return }
    
        await call.playTTS({ text: 'Welcome to SignalWire!' })
      }
    })
    
    consumer.run()
    

    Learn more about Relay Consumers

    Relay Task

    A Relay.Task is simple way to send jobs to your Relay.Consumers from a short lived process, like a web framework. Relay Tasks allow you to pass commands down to your Consumers without blocking your short lived request. Think of a Relay Task as a way to queue a job for your background workers to processes asynchronously.

    For example, if you wanted to make an outbound call and play a message when your user clicks a button on your web application, since Relay is a realtime protocol and relies on you to tell it what to do in realtime, if you did this within your web application, your web server would block until the call was finished... this may take a long time! Instead, simply create a new Relay Task. This task will be handled by a running Relay Consumer process and your web application can respond back to your user immediately.

    Send a task in the office context with custom data.

    // create-task.js
    const { Task } = require('@signalwire/node')
    
    async function main() {
      const yourTask = new Task('XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX', 'PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
      const context = 'office'
      const data = {
        uuid: 'unique id',
        data: 'data for your job'
      }
      try {
        await yourTask.deliver(context, data)
      } catch (error) {
        console.log('Error creating task!', error)
      }
    }
    
    main().catch(console.error)
    

    Handle the task in a Consumer.

    // consumer-task.js
    const { RelayConsumer } = require('@signalwire/node')
    
    const consumer = new RelayConsumer({
      project: 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX',
      token: 'PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
      contexts: ['office'],
      onTask: (message) => {
        console.log('Inbound task', message)
        // Retrieve your custom properties from 'message'..
        const { uuid, data } = message
      }
    })
    
    consumer.run()
    

    Learn more about Relay Tasks

    Relay Client

    Relay.Client is a lower level object, giving you a basic connection to Relay but that is all. It is best used when you are creating a script only concerned with sending outbound requests or you want complete control over the Relay connection yourself.

    Setting up a new client and make an outbound call.

    const { RelayClient } = require('@signalwire/node')
    const client = new RelayClient({
      project: 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX',
      token: 'PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    })
    
    client.on('signalwire.ready', async (client) => {
    
      const dialResult = await client.calling.dial({
        type: 'phone',
        from: '+1XXXXXXXXXX',
        to: '+1YYYYYYYYYY'
      })
    
      if (dialResult.successful) {
        const { call } = dialResult
        // Your call has been answered..
      }
    })
    
    client.connect()
    

    Learn more about Relay Clients

    Contexts

    Relay uses Contexts as a simple way to separate events to specific consumers, allowing you to write consumers for specific types of calls or messages or scale them independently. A Context is simply a named string, that allows you to categorize requests. When creating outbound requests, or configuring phone numbers for inbound requests, you can specify the context; Relay will then deliver that call or event to Consumers that are configured to listen for that context.

    For example, you could have a customer support phone number configured to send to Relay with the support context, and a personal number configured with personal context. Relay would deliver these events to any Consumer listening for those contexts. This gives you a lot of control in how messages are delivered to your Consumers, allowing you to write Consumer classes specific to the context, scale them independently, or separate traffic based on your own business rules.

    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

    project string required Project ID 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({
      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.
    messaging Relay.Messaging Returns a Relay.Messaging 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

    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

    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

    dial

    Make an outbound Call and waits until it has been answered or hung up.

    Available In:

    Parameters

    type string required The type of call. Only phone and sip are 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.
    headers Header[] optional SIP only. Array of Header objects like: { name: string, value: string }. Must be X- headers only, see example below.
    codecs string optional SIP 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_media boolean optional SIP only. If true, WebRTC media is negotiated. Default is parent leg setting.

    Returns

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

    Examples

    Make an outbound Call and grab the call object is it was answered.

    async function main() {
      const dialResult = await client.calling.dial({
        type: 'phone',
        from: '+1XXXXXXXXXX',
        to: '+1YYYYYYYYYY',
        timeout: 30
      })
    
      if (dialResult.successful) {
        const { call } = dialResult
      }
    }
    
    main().catch(console.error)
    

    Make an outbound Call to a SIP endpoint.

    async function main() {
      const dialResult = await client.calling.dial({
        type: 'sip',
        from: 'sip:XXXX@XXXXX.XXX',
        to: 'sip:YYYY@YYYYY.YYY',
        timeout: 30
      })
    
      if (dialResult.successful) {
        const { call } = dialResult
      }
    }
    
    main().catch(console.error)
    

    Dial a SIP endpoint with custom headers.

    client.calling.dial({
      type: 'sip',
      from: 'sip:XXXX@XXXXX.XXX',
      to: 'sip:YYYY@YYYYY.YYY',
      timeout: 30,
      headers: [{
        "name": "X-Relay-Call-ID",
        "value": "697a4e98-f452-416f-b11e-63c19112f542"
      }, {
        "name": "X-CID",
        "value": "124077399_129412436@206.117.11.72"
      }, {
        "name": "X-Target-Type",
        "value": "classic"
      }]
    })
    

    newCall

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

    Available In:

    Parameters

    See Relay.Calling.Dial for the parameter list.

    Returns

    Call - A new Relay.Calling.Call object.

    Examples

    Create a new Call object.

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

    Relay.Calling.AnswerResult

    This object returned from answer method.

    Properties

    successful boolean Whether the call has been answered from the remote party.
    event Relay.Event Last event that completed the operation.

    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 and sip are 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.
    context string The context the call belongs to.
    peer Relay.Calling.Call The call your original call is connected to.
    active boolean Whether the call is active.
    ended boolean Whether the call has ended.
    answered boolean Whether the call has been answered.
    failed boolean Whether the call has failed.
    busy boolean Whether the call was busy.

    Methods

    amd

    Alias for detectAnsweringMachine.

    amdAsync

    Alias for detectAnsweringMachineAsync.

    answer

    Answer an inbound call.

    Available In:

    Parameters

    None

    Returns

    Promise<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.

    Available In:

    Parameters

    params object required Object with the following properties:
    devices array required One or more objects with the structure below.
    Nested depends on whether to dial in serial or parallel.
    ringback object optional Ringback audio to play to call leg. You can play audio, tts, silence or ringtone. See play media parameter for details.
    • Structure of a device:
    type string required The device type. Only phone and sip are currently supported.
    from string optional The 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.
    to string required The party you are attempting to connect with.
    timeout number optional The time, in seconds, the call will ring before going to voicemail.
    headers {name: string, value: string}[] optional SIP only. Array of headers. Must be X- headers only.
    codecs string optional SIP 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_media boolean optional SIP only. If true, WebRTC media is negotiated. Default is parent leg setting.

    Returns

    Promise<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.

    Available In:

    Parameters

    See connect for the parameter list.

    Returns

    Promise<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)
    

    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.

    Available In:

    Parameters

    params object required Object to tune the detector with the following properties:
    • To detect an answering machine:
    type string required machine
    timeout number optional Number of seconds to run the detector.
    Defaults to 30.0.
    wait_for_beep boolean optional Whether to wait until the AM is ready for voicemail delivery.
    Defaults to false.
    initial_timeout number optional Number of seconds to wait for initial voice before giving up.
    Defaults to 4.5.
    end_silence_timeout number optional Number of seconds to wait for voice to finish.
    Defaults to 1.0.
    machine_voice_threshold number optional How many seconds of voice to decide is a machine.
    Defaults to 1.25.
    machine_words_threshold number optional How many words to count to decide is a machine.
    Defaults to 6.
    • To detect digits:
    type string required digit
    timeout number optional Number of seconds to run the detector.
    Defaults to 30.0.
    digits string optional The digits to detect.
    Defaults to "0123456789#*".
    • To detect a fax:
    type string required fax
    timeout number optional Number of seconds to run the detector.
    Defaults to 30.0.
    tone string optional The fax tone to detect: CED or CNG.
    Defaults to "CED".

    Returns

    Promise<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.

    Available In:

    Parameters

    See detect for the parameter list.

    Returns

    Promise<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.

    Available In:

    Parameters

    params object optional Object to tune the detector with the following properties:
    timeout number optional Number of seconds to run the detector.
    Defaults to 30.0.
    wait_for_beep boolean optional Whether to wait until the AM is ready for voicemail delivery.
    Defaults to false.
    initial_timeout number optional Number of seconds to wait for initial voice before giving up.
    Defaults to 4.5.
    end_silence_timeout number optional Number of seconds to wait for voice to finish.
    Defaults to 1.0.
    machine_voice_threshold number optional How many seconds of voice to decide is a machine.
    Defaults to 1.25.
    machine_words_threshold number optional How many words to count to decide is a machine.
    Defaults to 6.

    Returns

    React\Promise\Promise - 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.

    Available In:

    Parameters

    See detectAnsweringMachine for the parameter list.

    Returns

    React\Promise\Promise - 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.

    Available In:

    Parameters

    params object optional Object to tune the detector with the following properties:
    timeout number optional Number of seconds to run the detector.
    Defaults to 30.0.
    digits string optional The digits to detect.
    Defaults to "0123456789#*".

    Returns

    Promise<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.

    Available In:

    Parameters

    See detectDigit for the parameter list.

    Returns

    Promise<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.

    Available In:

    Parameters

    params object optional Object to tune the detector with the following properties:
    timeout number optional Number of seconds to run the detector.
    Defaults to 30.0.
    tone string optional The fax tone to detect: CED or CNG.
    Defaults to "CED".

    Returns

    Promise<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.

    Available In:

    Parameters

    See detectFax for the parameter list.

    Returns

    Promise<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)
    

    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: Use detectAnsweringMachine instead.

    Parameters

    params object required Object to tune the detector with the following properties:
    timeout number optional Number of seconds to run the detector.
    Defaults to 30.0.
    wait_for_beep boolean optional Whether to wait until the AM is ready for voicemail delivery.
    Defaults to false.
    initial_timeout number optional Number of seconds to wait for initial voice before giving up.
    Defaults to 4.5.
    end_silence_timeout number optional Number of seconds to wait for voice to finish.
    Defaults to 1.0.
    machine_voice_threshold number optional How many seconds of voice to decide is a machine.
    Defaults to 1.25.
    machine_words_threshold number optional How many words to count to decide is a machine.
    Defaults to 6.

    Returns

    Promise<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: Use detectAnsweringMachineAsync instead.

    Parameters

    See detectHuman for the parameter list.

    Returns

    Promise<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: Use detectAnsweringMachine instead.

    Parameters

    params object required Object to tune the detector with the following properties:
    timeout number optional Number of seconds to run the detector.
    Defaults to 30.0.
    wait_for_beep boolean optional Whether to wait until the AM is ready for voicemail delivery.
    Defaults to false.
    initial_timeout number optional Number of seconds to wait for initial voice before giving up.
    Defaults to 4.5.
    end_silence_timeout number optional Number of seconds to wait for voice to finish.
    Defaults to 1.0.
    machine_voice_threshold number optional How many seconds of voice to decide is a machine.
    Defaults to 1.25.
    machine_words_threshold number optional How many words to count to decide is a machine.
    Defaults to 6.

    Returns

    Promise<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: Use detectAnsweringMachineAsync instead.

    Parameters

    See detectMachine for the parameter list.

    Returns

    Promise<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)
    

    dial

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

    Available In:

    Parameters

    None

    Returns

    Promise<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)
    

    faxReceive

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

    Available In:

    Parameters

    None

    Returns

    Promise<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.

    Available In:

    Parameters

    None

    Returns

    Promise<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.

    Available In:

    Parameters

    document string required Http(s) URL to the document to send.
    PDF format only.
    identity string optional Identity to display on receiving fax.
    Defaults to SignalWire DID.
    header string optional Custom string to add to header of each fax page.
    Set to empty string to disable sending any header.

    Returns

    Promise<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.

    Available In:

    Parameters

    See faxSend for the parameter list.

    Returns

    Promise<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)
    

    hangup

    Hangup the call.

    Available In:

    Parameters

    None

    Returns

    Promise<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) {
    
    }
    

    on

    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

    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)
    

    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.

    Available In:

    Parameters

    params object required Object with the following properties:
    volume number optional Volume value between -40dB and +40dB where 0 is unchanged.
    Default is 0.
    media array required Array of media objects to play. See below for each type:
    • To play an audio file:
    type string required audio
    url string required Http(s) URL to audio resource to play.
    • To play a text to speech string:
    type string required tts
    text string required TTS to play.
    language string optional Default to en-US.
    gender string optional male or female. Default to female.
    • To play silence:
    type string required silence
    duration number required Seconds of silence to play.
    • To play ringtone:
    type string required ringtone
    name string required The name of the ringtone. See ringtones for the supported values.
    duration number optional Duration of ringtone to play.
    Default to 1 ringtone iteration.

    Returns

    Promise<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.

    Available In:

    Parameters

    See play for the parameter list.

    Returns

    Promise<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.

    Available In:

    Parameters

    params object required Object with the following properties:
    url string required Http(s) URL to audio resource to play.
    volume number optional Volume value between -40dB and +40dB where 0 is unchanged.
    Default is 0.

    Returns

    Promise<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. Require v2.3+

    // 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.

    Available In:

    Parameters

    See playAudio for the parameter list.

    Returns

    Promise<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)
    

    Play an Mp3 file setting the volume and stop it after 5 seconds.

    // within an async function ..
    const params = {
      url: 'https://cdn.signalwire.com/default-music/welcome.mp3',
      volume: 4
    }
    const playAction = await call.playAudioAsync(params)
    
    setTimeout(async () => {
      await playAction.stop()
    }, 5000)
    

    playRingtone

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

    Available In:

    Parameters

    params object required Object with the following properties:
    name string required The name of the ringtone. See ringtones for the supported values.
    duration number optional Duration of ringtone to play.
    Default to 1 ringtone iteration.
    volume number optional Volume value between -40dB and +40dB where 0 is unchanged.
    Default is 0.

    Returns

    Promise<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.

    Available In:

    Parameters

    See playRingtone for the parameter list.

    Returns

    Promise<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)
    

    playSilence

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

    Available In:

    Parameters

    duration number required Seconds of silence to play.

    Returns

    Promise<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.

    Available In:

    Parameters

    See playSilence for the parameter list.

    Returns

    Promise<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 await call.playSilenceAsync(60)
    
    if (Agent.available()) {
      await playAction.stop()
    }
    

    playTTS

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

    Available In:

    Parameters

    params object required Object with the following properties:
    text string required TTS to play.
    language string optional Default to en-US.
    gender string optional male or female. Default to female.
    volume number optional Volume value between -40dB and +40dB where 0 is unchanged.
    Default is 0.

    Returns

    Promise<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.

    Available In:

    Parameters

    See playTTS for the parameter list.

    Returns

    Promise<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)
    

    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.

    Available In:

    Parameters

    params object required Object with the following properties:
    type string required digits, speech or both.
    media array required List of media elements to play. See play parameters for the object structure.
    initial_timeout number optional Initial timeout in seconds.
    Default to 4 seconds.
    volume number optional Volume value between -40dB and +40dB where 0 is unchanged.
    Default is 0.
    • To collect digits:
    digits_max number required Max digits to collect.
    digits_terminators string optional DTMF digits that will end the recording.
    Default not set.
    digits_timeout number optional Timeout in seconds between each digit.
    • To collect speech:
    end_silence_timeout number optional How much silence to wait for end of speech.
    Default to 1 second.
    speech_timeout number optional Maximum time to collect speech.
    Default to 60 seconds.
    speech_language string optional Language to detect.
    Default to en-US.
    speech_hints array optional Array of expected phrases to detect.

    Returns

    Promise<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.

    Available In:

    Parameters

    See prompt for the parameter list.

    Returns

    Promise<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.

    Available In:

    Parameters

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

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

    The SDK will build the media for you.

    Returns

    Promise<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.

    Available In:

    Parameters

    See promptAudio for the parameter list.

    Returns

    Promise<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)
    

    promptRingtone

    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.

    Available In:

    Parameters

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

    name string required The name of the ringtone. See ringtones for the supported values.
    duration number optional Duration of ringtone to play.
    Default to 1 ringtone iteration.

    The SDK will build the media for you.

    Returns

    Promise<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.

    Available In:

    Parameters

    See promptRingtone for the parameter list.

    Returns

    Promise<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)
    

    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.

    Available In:

    Parameters

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

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

    The SDK will build the media for you.

    Returns

    Promise<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.

    Available In:

    Parameters

    See promptTTS for the parameter list.

    Returns

    Promise<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)
    

    record

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

    Available In:

    Parameters

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

    Returns

    Promise<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.

    Available In:

    Parameters

    See record for the parameter list.

    Returns

    Promise<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.

    Available In:

    Parameters

    params object required Object with the following properties:
    to string required SIP URI to transfer the call to.
    headers {name: string, value: string}[] optional Array of headers. Must be X-headers only.

    Returns

    Promise<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.

    Available In:

    Parameters

    See refer for the parameter list.

    Returns

    Promise<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.

    Available In:

    Parameters

    digits string required String 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<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.

    Available In:

    Parameters

    See sendDigits for the parameter list.

    Returns

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

    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.

    Available In:

    Parameters

    params object required Object with the following properties:
    audio_direction string required listen what the caller hears, speak what the caller says or both.
    target_type string required Protocol to use: rtp or ws, defaults to rtp.
    target_ptime number optional Packetization time in ms. It will be the same as the tapped media if not set.
    codec string optional Codec to use. It will be the same as the tapped media if not set.
    • To tap through RTP:
    target_addr string required RTP IP v4 address.
    target_port number required RTP port.

    Returns

    Promise<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.

    Available In:

    Parameters

    See tap for the parameter list.

    Returns

    Promise<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)
    

    waitFor

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

    Available In:

    Parameters

    event1, event2, ..eventN string or string[] required One or more Relay.Calling.Call state events

    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.

    Available In:

    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.

    Available In:

    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.

    Available In:

    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.

    Available In:

    Parameters

    None

    Returns

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

    Examples

    Wait for ending or ended events.

    // 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.

    stateChange Event dispatched when Call state changes.
    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.stateChange Event dispatched when the Call connect state changes.
    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.stateChange Event dispatched when the state of a playing changes.
    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.stateChange Event dispatched when the state of a recording changes.
    record.recording The call is being recorded.
    record.no_input The recording failed due to no input.
    record.finished The recording has ended.

    Refer Events

    To track a REFER state.

    refer.stateChange Event dispatched when the state of a refer process changes.
    refer.inProgress The transfer is in progress.
    refer.cancel The transfer has been cancelled.
    refer.busy The SIP endpoint is busy.
    refer.noAnswer The SIP endpoint did not answer.
    refer.error The refer attempt failed.
    refer.success The refer attempt succeeded.

    Prompt Events

    To track a prompt state.

    prompt The prompt action on the call has ended.

    Fax Events

    To track a fax state.

    fax.error Faxing failed.
    fax.finished Faxing has finished.
    fax.page A fax page has been sent or received.

    Detect Events

    To track a detector state.

    detect.error The detector has failed.
    detect.finished The detector has finished.
    detect.update There is a notification from the detector (eg: a new DTMF).

    Tap Events

    To track a tapping state.

    tap.tapping The tap action has started on the call.
    tap.finished Tap has finished.

    Digits Events

    To track a send digits action state.

    sendDigits.finished Digits have been sent.

    Ringtones

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

    name at, 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

    Relay.Calling.ConnectAction

    This object returned from connectAsync method that represents a connecting attempt that is currently active on a call.

    Properties

    result Relay.Calling.ConnectResult Final result of connecting.
    state string Current state of connecting attempt.
    completed boolean Whether the connection attempt has completed.
    payload object Payload sent to Relay to start the connect.

    Relay.Calling.ConnectResult

    This object returned from connect method that represents the final result of a connection between your call and a remote one.

    Properties

    successful boolean Whether the call has been connected successfully.
    event Relay.Event Last event that completed the operation.
    call Relay.Calling.Call Remote Call connected with yours.

    Relay.Calling.DetectAction

    This object returned from one of the asynchronous detect methods that represents a running detector on the call.

    Properties

    result Relay.Calling.DetectResult Final detector result.
    completed boolean Whether the action has finished.
    payload object Payload sent to Relay to start this detector.
    controlId string UUID to identify the detector.

    Methods

    stop

    Stop the action immediately.

    Available In:

    Parameters

    None

    Returns

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

    Examples

    Trying to detect a machine and stop the action after 5 seconds.

    async function main() {
      const detectAction = await call.detectMachineAsync()
    
      // For demonstration purposes only..
      setTimeout(async () => {
        const stopResult = await detectAction.stop()
      }, 5000)
    }
    
    main().catch(console.error)
    

    Relay.Calling.DetectResult

    This object returned from one of the synchronous detect methods that represents the final result of a detector.

    Properties

    successful boolean Whether the detector has finished successfully.
    event Relay.Event Last event that completed the operation.
    type string The detector type: fax, machine or digit.
    result string The final detector result.

    Relay.Calling.DialResult

    This object returned from dial method.

    Properties

    successful boolean Whether the remote party has picked up your call.
    event Relay.Event Last event that completed the operation.
    call Relay.Calling.Call Reference to the Call.

    Relay.Calling.FaxAction

    This object returned from faxReceiveAsync and faxSendAsync methods represents a receiving or sending Fax on the call.

    Properties

    result Relay.Calling.FaxResult Final result for the fax action.
    completed boolean Whether the action has finished.
    payload object Payload sent to Relay to start faxing.
    controlId string UUID to identify the fax action.

    Methods

    stop

    Stop the action immediately.

    Available In:

    Parameters

    None

    Returns

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

    Examples

    Start sending fax and stop 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')
    
      // For demonstration purposes only..
      setTimeout(async () => {
        const stopResult = await faxAction.stop()
      }, 5000)
    }
    
    main().catch(console.error)
    

    Relay.Calling.FaxResult

    This object returned from faxReceive and faxSend methods that represents the final result of a sent or received Fax.

    Properties

    successful boolean Whether the fax has been sent or received successfully.
    event Relay.Event Last event that completed the operation.
    direction string send or receive.
    identity string Identity used to send the fax.
    remoteIdentity string Remote identity.
    document string Document URL.
    pages number Number of sent/received pages.

    Relay.Calling.HangupResult

    This object returned from hangup method.

    Properties

    successful boolean Whether the call has been hung up successfully.
    event Relay.Event Last event that completed the operation.
    reason string The hangup reason.

    Relay.Calling.PlayAction

    This object returned from one of asynchronous play methods that represents a playing currently active on a call.

    Properties

    result Relay.Calling.PlayResult Final result of playing.
    state string Current state of playing.
    completed boolean Whether the playing has finished.
    payload object Payload sent to Relay to start playing.
    controlId string UUID to identify the playing.

    Methods

    pause

    Pause the playback immediately.

    Available In:

    Parameters

    None

    Returns

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

    Examples

    Start playing an audio file and pause it after 5 seconds.

    // Promise to wait some seconds..
    const sleep = (seconds) => new Promise(resolve => setTimeout(resolve, seconds*1000))
    
    async function main() {
      const playAction = await call.playAudioAsync('https://cdn.signalwire.com/default-music/welcome.mp3')
      await sleep(5)
      const pauseResult = await playAction.pause()
    }
    
    main().catch(console.error)
    

    resume

    Resume the playback immediately.

    Available In:

    Parameters

    None

    Returns

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

    Examples

    Start playing an audio file, stop it and then resume it after 5 seconds.

    // Promise to wait some seconds..
    const sleep = (seconds) => new Promise(resolve => setTimeout(resolve, seconds*1000))
    
    async function main() {
      const playAction = await call.playAudioAsync('https://cdn.signalwire.com/default-music/welcome.mp3')
      await sleep(5)
      const pauseResult = await playAction.pause()
      await sleep(5)
      const resumeResult = await playAction.resume()
    }
    
    main().catch(console.error)
    

    stop

    Stop the action immediately.

    Available In:

    Parameters

    None

    Returns

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

    Examples

    Start playing an audio file and stop it after 5 seconds.

    async function main() {
      const playAction = await call.playAudioAsync('https://cdn.signalwire.com/default-music/welcome.mp3')
    
      setTimeout(async () => {
        const stopResult = await playAction.stop()
      }, 5000)
    }
    
    main().catch(console.error)
    

    volume

    Control the volume of the playback.

    Available In:

    Parameters

    volume number required Volume value between -40dB and +40dB where 0 is unchanged.

    Returns

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

    Examples

    Start playing an audio file and increase the playback volume.

    async function main() {
      const playAction = await call.playAudioAsync('https://cdn.signalwire.com/default-music/welcome.mp3')
      const volumeResult = await playAction.volume(5.0)
    }
    
    main().catch(console.error)
    

    Relay.Calling.PlayPauseResult

    This object is returned by pause method and represents the final result of a play pause operation.

    Properties

    successful boolean Whether the playing has been paused successfully.

    Relay.Calling.PlayResult

    This object returned from one of the synchronous play methods that represents the final result of a playing.

    Properties

    successful boolean Whether the playing has completed successfully.
    event Relay.Event Last event that completed the operation.

    Relay.Calling.PlayResumeResult

    This object is returned by resume method and represents the final result of a play resume operation.

    Properties

    successful boolean Whether the playing has resumed successfully.

    Relay.Calling.PlayVolumeResult

    This object is returned by volume method and represents the final result of a volume control operation.

    Properties

    successful boolean Whether the playing volume has been changed successfully.

    Relay.Calling.PromptAction

    This object returned from one of asynchronous prompt methods that represents a prompt attempt that is currently active on a call.

    Properties

    result Relay.Calling.PromptResult Final result of this prompt.
    state string Current state.
    completed boolean Whether the prompt attempt has finished.
    payload object Payload sent to Relay to start prompt.
    controlId string UUID to identify the prompt.

    Methods

    stop

    Stop the action immediately.

    Available In:

    Parameters

    None

    Returns

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

    Examples

    Ask user to enter a PIN and force-stop the action after 5 seconds.

    async function main() {
      const collect = {
        type: 'digits',
        digits_max: 3,
        initial_timeout: 10,
        text: 'Please, enter your 3 digit PIN.'
      }
      const action = await call.promptTTSAsync(collect)
    
      // ...
    
      setTimeout(async () => {
        const stopResult = await action.stop()
      }, 5000)
    }
    
    main().catch(console.error)
    

    volume

    Control the volume of the playback.

    Available In:

    Parameters

    volume number required Volume value between -40dB and +40dB where 0 is unchanged.

    Returns

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

    Examples

    Start the prompt and increase the playback volume.

    async function main() {
      const collect = {
        type: 'digits',
        digits_max: 3,
        text: 'Please, enter your 3 digit PIN.'
      }
      const action = await call.promptTTSAsync(collect)
    
      const volumeResult = await action.volume(5.0)
    }
    
    main().catch(console.error)
    

    Relay.Calling.PromptResult

    This object returned from one of the synchronous prompt methods that represents the final result of a prompting attempt.

    Properties

    successful boolean Whether the attempt has completed successfully.
    event Relay.Event Last event that completed the operation.
    type string digit or speech.
    result string Result of prompt attempt.
    terminator string Digit that terminated the prompt.
    confidence number Confidence of the result on a speech prompt.

    Relay.Calling.PromptVolumeResult

    This object is returned by volume method and represents the final result of a volume control operation.

    Properties

    successful boolean Whether the volume has been changed successfully.

    Relay.Calling.RecordAction

    This object returned from recordAsync method that represents a recording currently active on a call.

    Properties

    result Relay.Calling.RecordResult Final result of recording.
    state string Current state of recording.
    url string HTTPS URL to the recording file.
    It may not be present at the URL until the recording is finished.
    completed boolean Whether the recording has finished.
    payload object Payload sent to Relay to start recording.
    controlId string UUID to identify the recording.

    Methods

    stop

    Stop the action immediately.

    Available In:

    Parameters

    None

    Returns

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

    Examples

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

    async function main() {
      const action = await call.recordAsync({
        stereo: true
      })
    
      if (Agent.isAvailable() === false) {
        const stopResult = await action.stop()
      }
    }
    
    main().catch(console.error)
    

    Relay.Calling.RecordResult

    This object returned from record method that represents the final result of a recording.

    Properties

    successful boolean Whether the recording has completed successfully.
    event Relay.Event Last event that completed the operation.
    url string HTTPS URL to the recording file.
    duration number Duration of the recording in seconds.
    size number Size of the recording.

    Relay.Calling.ReferAction

    This object returned from referAsync method that represents an async refer attempt.

    Properties

    result Relay.Calling.RecordResult Final result of refer.

    Relay.Calling.ReferResult

    This object returned from refer method that represents the final result of a SIP REFER.

    Properties

    successful boolean Whether the recording has completed successfully.
    event Relay.Event Last event that completed the operation.
    referTo string The SIP URI the call is transferred to.
    referResponseCode string SIP response to the REFER request.
    referNotifyCode string SIP response to the NOTIFY received after the REFER.

    Relay.Calling.SendDigitsAction

    This object is returned by the sendDigitsAsync method and represents a send digits action currently active on a call.

    Properties

    result Relay.Calling.SendDigitsResult Final result of the action.
    state string Current state of the action.
    completed boolean Whether the action has finished.
    payload object Payload sent to Relay to start the action.
    controlId string UUID to identify the action.

    Relay.Calling.SendDigitsResult

    This object is returned by the sendDigits method and represents the final result of the action.

    Properties

    successful boolean Whether the action has completed successfully.
    event Relay.Event Last event that completed the operation.

    Relay.Calling.StopResult

    This object is returned from one the synchronous stop methods on an action when an asynchronous operation is being stopped, which represent the final result of a stop operation.

    Properties

    successful boolean Whether the stop operation has completed successfully.

    Relay.Calling.TapAction

    This object returned from tapAsync method that represents the running media tapping active on a call.

    Properties

    result Relay.Calling.TapResult Final tap result.
    state string Current state of tapping.
    completed boolean Whether the tapping has finished.
    payload object Payload sent to Relay to start tapping.
    controlId string UUID to identify the action.
    sourceDevice object Source device sending media.

    Methods

    stop

    Stop the action immediately.

    Available In:

    Parameters

    None

    Returns

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

    Examples

    Start tapping using RTP and stop it after 5 seconds.

    async function main() {
      const action = await call.tapAsync({
        target_type: 'rtp',
        target_addr: '192.168.1.1',
        target_port: 1234
      })
    
      setTimeout(async () => {
        const stopResult = await action.stop()
      }, 5000)
    }
    
    main().catch(console.error)
    

    Relay.Calling.TapResult

    This object returned from tap method that represents the final result of a tapping.

    Properties

    successful boolean Whether the tapping has completed successfully.
    event Relay.Event Last event that completed the operation.
    tap object Object with payload for this action.
    sourceDevice object Source device sending media.
    destinationDevice object Destination device receiving media.

    Relay.Consumer

    A Relay Consumer is a simple Node object that runs in its own process along side your application to handle calling and messaging events in realtime. Relay Consumers abstract all the setup of connecting to Relay and automatically dispatch workers to handle requests. Consumers will receive requests and delegate them to their own worker thread, allowing you to focus on your business logic without having to worry about multi-threading or blocking, everything just works. Think of Relay Consumers like a background worker system for all your calling and messaging needs.

    Creating Consumers

    A Relay Consumer is a simple object, customized by specifying contexts and event handlers to respond to incoming events.

    A consumer has 2 required properties: project, token, and usually requires at least one contexts for incoming events. Project and Token are used to authenticate your Consumer to your SignalWire account. Contexts are a list of contexts you want this Consumer to listen for. Learn more about Contexts.

    const { RelayConsumer } = require('@signalwire/node')
    
    const consumer = new RelayConsumer({
      project: 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX',
      token: 'PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
      contexts: ['default'],
      onIncomingCall: async (call) => {
        await call.answer()
        await call.playTTS({ text: 'Welcome to SignalWire!' })
      }
    })
    
    consumer.run()
    

    Initializing Consumers

    You can optionally add an setup method if you need to do any initialization work before processing messages. This is useful to do any one-off work that you wouldn't want to do for each and every event, such as setting up logging or connecting to a datastore.

    const { RelayConsumer } = require('@signalwire/node')
    
    const consumer = new RelayConsumer({
      project: 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX',
      token: 'PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
      contexts: ['default'],
      setup: (consumer) => {
        // Initialize anything you'd like available for all events.
        // Like logging, database connections, etc.
      },
      onIncomingCall: async (call) => {
        await call.answer()
        await call.playTTS({ text: 'Welcome to SignalWire!' })
      }
    })
    
    consumer.run()
    

    Properties

    client Relay.Client The underlying Relay client object.

    Note: you can access the properties from every Consumer methods using this keyword only if you are using functions instead of arrow functions.

    Event Handlers

    Event handlers are where you will write most of your code. They are executed when your consumer receives a matching event for the contexts specified by your Consumer.

    ready

    Executed once your Consumer is connected to Relay and the session has been established. It passes in the Consumer object itself.

    Available In:

    const { RelayConsumer } = require('@signalwire/node')
    
    const consumer = new RelayConsumer({
      project: 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX',
      token: 'PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
      contexts: ['default'],
      ready: async (consumer) => {
        const { client } = consumer
        const { successful, call } = await client.calling.dial({
          type: 'phone',
          from: '+1XXXXXXXXXX',
          to: '+1YYYYYYYYYY',
          timeout: 30
        })
    
        if (successful) {
          // Use call ...
        }
      }
    })
    
    consumer.run()
    

    onIncomingCall

    Executed when you receive an inbound call, passes in the inbound Call object.

    Available In:

    const { RelayConsumer } = require('@signalwire/node')
    
    const consumer = new RelayConsumer({
      project: 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX',
      token: 'PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
      contexts: ['default'],
      onIncomingCall: async (call) => {
        await call.answer()
        await call.playTTS({ text: 'Welcome to SignalWire!' })
      }
    })
    
    consumer.run()
    

    onTask

    Executed with your message sent through a Relay.Task.

    Available In:

    const { RelayConsumer } = require('@signalwire/node')
    
    const consumer = new RelayConsumer({
      project: 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX',
      token: 'PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
      contexts: ['default'],
      onTask: async (message) => {
        console.log('Inbound task', message)
        // ..Use your own 'message' sent in the context "default" from a Relay.Task
      }
    })
    
    consumer.run()
    

    onIncomingMessage

    Executed when you receive an inbound SMS or MMS, passes in the inbound Message object.

    Available In:

    const { RelayConsumer } = require('@signalwire/node')
    
    const consumer = new RelayConsumer({
      project: 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX',
      token: 'PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
      contexts: ['default'],
      onIncomingMessage: async (message) => {
        // Handle the inbound message here..
        console.log('Received message', message.id, message.context)
      }
    })
    
    consumer.run()
    

    onMessageStateChange

    Executed when a message state changes, passes in the inbound Message object.

    Available In:

    const { RelayConsumer } = require('@signalwire/node')
    
    const consumer = new RelayConsumer({
      project: 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX',
      token: 'PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
      contexts: ['default'],
      ready: async ({ client }) => {
        // Once the Consumer is ready send an SMS
        const params = {
          context: 'office',
          from: '+1yyy',
          to: '+1xxx',
          body: 'Welcome at SignalWire!' }
        const { successful, messageId } = await client.messaging.send(params)
        if (successful) {
          console.log('Message ID: ', messageId)
        } else {
          console.error('Error sending the SMS')
        }
      },
      onMessageStateChange: async (message) => {
        // Keep track of your SMS state changes..
        console.log('Message state change', message.id, message.state)
      }
    })
    
    consumer.run()
    

    Cleaning Up on Exit

    When a Relay Consumer shuts down, you have the opportunity to clean up any resources held by the consumer. For example, you could close any open files, network connections, or send a notification to your monitoring service.

    Just implement a teardown method in your consumer and it will be called during the shutdown procedure.

    const { RelayConsumer } = require('@signalwire/node')
    
    const consumer = new RelayConsumer({
      project: 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX',
      token: 'PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
      contexts: ['default'],
      onIncomingCall: async (call) => {
        await call.answer()
        await call.playTTS({ text: 'Welcome to SignalWire!' })
      },
      teardown: () => {
        // Clean up any resources when exiting.
      },
    })
    
    consumer.run()
    

    Running Consumers

    Running a consumer is just like running any Node.js script, simply execute the script as a separate process and ensure you have .run() at the end of your script. The process will stay up until you shut it down.

    Shutting Down Consumers

    In order to gracefully shut down a Relay consumer process, send it the SIGTERM signal. Most process supervisors such as Runit, Docker and Kubernetes send this signal when shutting down a process, so using those systems will make things easier.

    Relay.Event

    This object represents the last Relay event that completed an operation on the Call.

    Properties

    name string The event name.
    payload object Raw JSON object of the Relay event.

    Relay.Messaging

    This represents the API interface for the Messaging Relay Service. This object is used to make requests related to managing SMS and MMS messages.

    Methods

    send

    Send an outbound SMS or MMS message.

    Available In:

    Parameters

    context string required The context to receive inbound events.
    from string required The phone number to place the message from. Must be a SignalWire phone number or short code that you own.
    to string required The phone number to send to.
    body string required The content of the message.
    Optional if media is present.
    media string[] required Array of URLs to send in the message.
    Optional if body is present.
    tags string[] optional Array of strings to tag the message with for searching in the UI.

    Returns

    Promise<SendResult> - Promise that will be fulfilled with a Relay.Messaging.SendResult object.

    Examples

    Send a message in the context office.

    async function main() {
      const sendResult = await client.messaging.send({
        context: 'office',
        from: '+1XXXXXXXXXX',
        to: '+1YYYYYYYYYY',
        body: 'Welcome at SignalWire!'
      })
    
      if (sendResult.successful) {
        console.log('Message ID: ', sendResult.messageId)
      }
    }
    
    main().catch(console.error)
    

    Relay.Messaging.Message

    An object representing an SMS or MMS message. It is the parameter of both onIncomingMessage and onMessageStateChange Consumer handlers.

    Properties

    id string The unique identifier of the message.
    context string The context of the message.
    from string The phone number the message comes from.
    to string The destination number of the message.
    direction string The direction of the message: inbound or outbound.
    state string The current state of the message. See Relay.Messaging.Message State Events for all the possible states.
    body string The content of the message.
    media string[] Array of URLs media.
    tags string[] Array of strings with message tags.
    segments number Number of segments of the message.
    reason string Reason why the message was not sent.
    Present only in case of failure.

    Events

    State Events

    To track the state of a message.

    queued The message has been queued in Relay.
    initiated Relay has initiate the process to send the message.
    sent Relay has sent the message.
    delivered The message has been successfully delivered. Due to the nature of SMS and MMS, receiving a delivered event is not guaranteed, even if the message is delivered successfully.
    undelivered The message has not been delivered. Due to the nature of SMS and MMS, receiving a undelivered event is not guaranteed, even if the message fails to be delivered.
    failed The call has failed.

    Relay.Messaging.SendResult

    This object returned from send method that represents the result of a send operation.

    Properties

    successful boolean Whether the send operation has successfully queued the message.
    messageId string The ID of the message.

    Relay.Task

    A Relay.Task is simple way to send jobs to your Relay.Consumers from a short lived process, like a web framework. Relay Tasks allow you to pass commands down to your Consumers without blocking your short lived request. Think of a Relay Task as a way to queue a job for your background workers to processes asynchronously.

    Creating Tasks

    A Task is a simple object with 2 required arguments: project and token. Project and Token are used to send the Task to your Consumers. Once created, the Task has only one method deliver to send jobs to your Consumer.

    const { Task } = require('@signalwire/node')
    
    const yourTask = new Task('XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX', 'PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
    const context = 'office'
    yourTask.deliver(context, { 'key': 'value', 'data': 'data for your job' })
      .then(() => {
        console.log('Task created successfully!')
      })
      .catch((error) => {
        console.log('Error creating task!', error)
      })
    

    Methods

    deliver

    Send a job to your Consumer in a specific context.

    Available In:

    Parameters

    context string required Context where to send the Task.
    message object required Object with your custom data that will be sent to your Consumer's onTask handler.

    Returns

    Promise - Promise resolved in case of success, rejected otherwise.

    Examples

    Deliver a task to your Consumer with a message to then make an outbound Call.

    const message = {
      'action': 'call',
      'from': '+18881112222'
      'to': '+18881113333'
    }
    task.deliver('office', message).then(() => {
      console.log('Task created successfully!')
    })
    .catch((error) => {
      console.log('Error creating task!', error)
    })
    

    Examples

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

    Inbound Calls

    Using RelayConsumer to manage inbound calls from both home and office contexts. Answer the call, ask the user to enter his PIN and playback the digits he sent if successful.

    const { RelayConsumer } = require('@signalwire/node')
    
    const consumer = new RelayConsumer({
      project: 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX',
      token: 'PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
      contexts: ['home', 'office'],
      onIncomingCall: async (call) => {
        const { successful } = await call.answer()
        if (!successful) {
          console.error('Answer Error')
          return
        }
    
        const collect = {
          type: 'digits',
          digits_max: 3,
          text: 'Welcome to SignalWire! Please, enter your 3 digits PIN'
        }
        const prompt = await call.promptTTS(collect)
        if (prompt.successful) {
          await call.playTTS({ text: `You entered: ${prompt.result}. Thanks and good bye!` })
        }
        await call.hangup()
      }
    })
    
    consumer.run()
    

    Outbound Calls

    Using RelayConsumer to make a call and ask user to enter the PIN. When the prompt has completed, logs the result.

    const { RelayConsumer } = require('@signalwire/node')
    
    const consumer = new RelayConsumer({
      project: 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX',
      token: 'PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
      contexts: ['home', 'office'],
      ready: async (consumer) => {
        const dialResult = await consumer.client.calling.dial({
          type: 'phone',
          from: '+1XXXXXXXXXX', // Must be a number in your SignalWire Space
          to: '+1YYYYYYYYYY'
        })
        const { successful, call } = dialResult
        if (!successful) {
          console.error('Dial error..')
          return
        }
    
        const prompt = await call.promptTTS({
          type: 'digits',
          digits_max: 3,
          text: 'Welcome to SignalWire! Enter your 3 digits PIN'
        })
    
        if (prompt.successful) {
          console.log(`User digits: ${prompt.result}`)
        }
      }
    })
    
    consumer.run()