Navbar
Logo icon Name
  • Relay SDK for Ruby
  • API Reference
  • Relay SDK for Ruby

    Getting Started

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

    The Relay SDK for Ruby is easy to use and only takes a few minutes to setup and get running.

    Latest Version:

    Source Code: signalwire/signalwire-ruby

    Support: SignalWire Community Slack Channel

    Installation

    Install the gem using RubyGems:

    gem install signalwire
    

    Or add it to your Gemfile

    gem "signalwire"
    

    Then require it in your scripts:

    require "signalwire"
    

    Minimum Requirements

    The Relay SDK gem requires Ruby version 2.0 or higher.

    Using the SDK

    The Ruby SDK requires your project and token from your SignalWire dashboard. Credentials can be passed in to initializers, or you can set the SIGNALWIRE_PROJECT_KEY and SIGNALWIRE_TOKEN environment variables and they will be automatically picked up by the client.

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

    The recommended starting point is the Relay.Consumer class, and Relay.Client provides lower-level access.

    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.

    require "signalwire"
    
    class MyConsumer < Signalwire::Relay::Consumer
      contexts ['incoming']
    
      def on_incoming_call(call)
        call.answer
        call.play_tts 'the quick brown fox jumps over the lazy dog'
        call.hangup
      end
    end
    
    MyConsumer.new.run
    

    Learn more about Relay Consumers

    Relay Task

    A SignalWire::Relay::Task is a simple way to send jobs to your Relay.Consumer 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.

    require 'signalwire/relay/task'
    
    task = Signalwire::Relay::Task.new(project: "your-project-id", token: "your-project-token")
    task.deliver(context: 'incoming', message: { number_to_call: '+1555XXXXXXX', message_to_play: 'We have a message for you' })
    

    Learn more about Relay Tasks

    Relay Client

    Relay.Client is the underlying Relay connection Consumers use. It offers an alternative API for cases that require more specialized functionality.

    Setting up a new client and make an outbound call.

    require "signalwire"
    
    client = Signalwire::Relay::Client.new(project: "your-project-id", token: "your-project-token")
    
    client.on :ready do
      call_handle = client.calling.new_call(from: "+1XXXXXXXXXX", to: "+1YYYYYYYYYY")
      call_handle.on :answered do
        # your call has been answered
      end
    end
    
    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 configuing 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.

    Signalwire::Relay::Client.new(project: "your-project-id", token: "your-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!

    Starts 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.
    client.connect!
    

    disconnect!

    Disconnect the client from Relay.

    Available In:

    Returns

    nil

    Examples

    client.disconnect!
    

    on

    Attach an event handler for a specific type of event.

    Available In:

    Parameters

    event Symbol required Event name. Full list of events Relay::Client Events
    guards Array optional Guard clauses for the event.
    handler Block optional Block to call when the event is received. It will be passed in as an argument.

    Returns

    String - A low-level handler ID.

    Examples

    Subscribe to the ready event.

    client.on :ready do
      # do something on ready
    end
    

    Events

    All available events you can attach a listener on.

    :ready The session has been established and all other methods can now be used.
    :event The session has received a Relay event.

    Relay::Calling

    This namespace represents the API interface for the Calling Relay Service. It 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

    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.
    type String optional The type of call. Only phone is currently supported.
    timeout Numeric optional The time, in seconds, the call will ring before going to voicemail.

    Returns

    Relay::Calling::DialResult - returned upon answer or failure of the dialed call.

    Examples

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

    call_result = client.dial(from: "+1XXXXXXXXXX", to: "+1YYYYYYYYYY")
    
    if call_result.successful
      call = call_result.call
    end
    

    new_call

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

    Available In:

    Parameters

    See Relay::Calling::Dial for the parameter list.

    Returns

    Relay::Calling::Call - A new call object.

    Examples

    Create a new Call object then dial.

    call = client.calling.new_call(
      type: 'phone',
      from: '+1XXXXXXXXXX',
      to: '+1YYYYYYYYYY',
      timeout: 30
    )
    
    # Do some pre-dialing setup.
    
    # Start dialing the destination.
    call.dial
    

    Relay::Calling::AnswerResult

    This object is returned by the 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 is currently supported.
    from String The phone number that the call is coming from.
    to String The phone number you are attempting to call.
    timeout Numeric 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 is busy.

    Methods

    answer

    Answer an inbound call.

    Available In:

    Parameters

    None

    Returns

    Relay::Calling::AnswerResult - The result object to interact with.

    Examples

    Answer an inbound call and check if it was successful.

    result = call.answer
    
    if result.successful
      #call was answered
    end
    

    connect

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

    You can connect to multiple devices in series, parallel, or any combination of both. Series means one device is dialed at a time, while parallel implies multiple devices ring at the same time.

    Available In:

    Parameters

    device1, device2, ..deviceN Array required An array of devices, passed in as hashes with the following properties. Nesting depends on whether the dialing is in serial or parallel. Only phone devices are currently supported.
    ringback Hash optional Ringback audio to play to call leg. You can play audio, tts, silence or ringtone. See play media parameter for details.

    To dial a phone number:

    type String required phone
    params Hash required Parameters that specify the call parties:
    params.from_number String optional The party the call is coming from.
    If not provided, the SDK will use the from property of the originating call.
    Must be a SignalWire number or SIP endpoint that you own.
    params.to_number String required The party you are attempting to connect with.
    timeout Numeric optional The time, in seconds, the call will ring before being canceled. Defaults to 30

    Returns

    Relay::Calling::ConnectResult - The result object to interact with.

    Examples

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

    connected = call.connect [
      [{ type: 'phone', params: { to_number: '+18991114444', from_number: "+1YYYYYYYYYY", timeout: 30 } }],
      [{ type: 'phone', params: { to_number: '+18991115555', from_number: "+1YYYYYYYYYY", timeout: 30 } }]
    ]
    
    if connected.successful
      # connected.call is the remote leg connected with yours.
      connected.call.wait_for_ended
    end
    
    call.hangup
    

    Trying to connect a call by calling +18991114444 and +18991115555 in series, playing the US ringtone.

    connected = call.connect(devices: [
        [{ type: 'phone', params: { to_number: '+18991114444', from_number: "+1YYYYYYYYYY", timeout: 30 } }],
        [{ type: 'phone', params: { to_number: '+18991115555', from_number: "+1YYYYYYYYYY", timeout: 30 } }]
      ],
      ringback: { type: 'ringtone', name: 'us' }
    )
    
    if connected.successful
      # connected.call is the remote leg connected with yours.
      connected.call.wait_for_ended
    end
    
    call.hangup
    

    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.

     connected = call.connect [
        [{ type: 'phone', params: { to_number: '+18991114443', from_number: "+1YYYYYYYYYY", timeout: 30 } }],
        [
          { type: 'phone', params: { to_number: '+18991114444', from_number: "+1YYYYYYYYYY", timeout: 30 } },
          { type: 'phone', params: { to_number: '+18991114445', from_number: "+1YYYYYYYYYY", timeout: 30 } },
        ],
        [
          { type: 'phone', params: { to_number: '+18991114446', from_number: "+1YYYYYYYYYY", timeout: 30 } },
          { type: 'phone', params: { to_number: '+18991114447', from_number: "+1YYYYYYYYYY", timeout: 30 } },
        ]
      ]
    
      if connected.successful
        # connected.call is the remote leg connected with yours.
        connected.call.wait_for_ended
      end
    
      call.hangup
    

    connect!

    Asynchronous version of connect. It does not wait for the connect to complete or fail, and it immediately returns a ConnectAction object you can interact with.

    Available In:

    Parameters

    See connect for the parameter list.

    Returns

    Relay::Calling::ConnectAction - The action object to interact with.

    Examples

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

    connected = call.connect! [
      [{ type: 'phone', params: { to_number: '+18991114444', from_number: "+1YYYYYYYYYY", timeout: 30 } }],
      [{ type: 'phone', params: { to_number: '+18991114445', from_number: "+1YYYYYYYYYY", timeout: 30 } }]
    ]
    
    # asynchronous code that executes in parallel with the dial
    
    if connected.completed
      #the call is now connected
    end
    

    detect

    Starts 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 detect_digit, detect_fax, detect_human or detect_machine for more specific usage.

    Available In:

    Parameters

    type String optional Type of detector to start: machine, fax or digit. Defaults to machine.
    timeout Numeric optional Number of seconds to run the detector.
    Defaults to 30.0s.
    • When type is machine:

      initial_timeout Numeric optional Number of seconds to wait for initial voice before giving up.
      Valid when type is machine.
      Defaults to 4.5.
      end_silence_timeout Numeric optional Number of seconds to wait for voice to finish.
      Valid when type is machine.
      Defaults to 1.0.
      machine_voice_threshold Numeric optional How many seconds of speech to return MACHINE.
      Valid when type is machine.
      Defaults to 1.25.
      machine_words_threshold Numeric optional How many words to count to return MACHINE.
      Valid when type is machine.
      Defaults to 6.
    • When type is fax:

      tone String optional The tone to detect: CED or CNG.
      Valid when type is fax.
      Defaults to "CED".
    • When type is digits:

      digits String optional The digits to detect.
      Valid when type is digit.
      Defaults to "0123456789#*".

    Returns

    Relay::Calling::DetectResult - The result object to interact with.

    Examples

    Detect with custom parameters and timeout.

    result = call.detect(type: :digit, digits: "345" timeout: 10)
    logger.debug "User pressed #{result.result}"
    

    Detect a Fax setting timeout only.

    result = call.detect(type: :fax, detect: detect)
    puts "fax detected" if result.successful
    

    detect!

    Asynchronous version of detect. It does not wait for the detector to stop, and returns a DetectAction object you can interact with.

    Available In:

    Parameters

    See detect for the parameter list.

    Returns

    Relay::Calling::DetectAction - The action object to interact with.

    Examples

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

    action = call.detect!(type: :digit, digits: "345" timeout: 10)
    sleep 5
    action.stop
    

    detect_answering_machine

    This is a helper function that refines the use of detect. It is used to detect a machine, and is intended to replace the deprecated methods.

    Available In:

    Parameters

    initial_timeout Numeric optional Number of seconds to wait for initial voice before giving up.
    Defaults to 4.5.
    end_silence_timeout Numeric optional Number of seconds to wait for voice to finish..
    Defaults to 1.0.
    machine_voice_threshold Numeric optional How many seconds of speech to return MACHINE.
    Defaults to 1.25.
    machine_words_threshold Numeric optional How many words to count to return MACHINE.
    Defaults to 6.
    timeout Numeric optional Number of seconds to run the detector.
    Defaults to 30.0s.

    Returns

    Relay::Calling::DetectResult - The result object to interact with.

    Examples

    Detect a machine and log the result.

    result = call.detect_answering_machine(initial_timeout: 10, timeout: 10)
    logger.debug "Detect result was #{result.result}"
    

    detect_answering_machine!

    Asynchronous version of detect_answering_machine. It does not wait the detector ends but returns a DetectAction object you can interact with.

    Available In:

    Parameters

    See detect_answering_machine for the parameter list.

    Returns

    Relay::Calling::DetectAction - The action object to interact with.

    Examples

    Detect a machine. Stop the action after 5 seconds.

    action = call.detect_answering_machine!(initial_timeout: 10, timeout: 10)
    sleep 5
    action.stop
    

    amd

    Alias of detect_answering_machine.

    Available In:

    Parameters

    See detect_answering_machine for the parameter list.

    Returns

    Relay::Calling::DetectResult - The result object to interact with.

    amd!

    Alias of the asynchronous detect_answering_machine! method.

    Available In:

    Parameters

    See detect_answering_machine for the parameter list.

    Returns

    Relay::Calling::DetectAction - The action object to interact with.

    detect_digit

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

    Available In:

    Parameters

    digits String optional The digits to detect.
    Defaults to "0123456789#*".
    timeout Numeric optional Number of seconds to run the detector.
    Defaults to 30.0s.

    Returns

    Relay::Calling::DetectResult - The result object to interact with.

    Examples

    Detect digits and then write a log with the result.

    result = call.detect_digit(digits: "345", timeout: 10)
    logger.debug "User pressed #{result.result}"
    

    detect_digit!

    Asynchronous version of detect_digit. It does not wait the detector ends but returns a DetectAction object you can interact with.

    Available In:

    Parameters

    See detect_digit for the parameter list.

    Returns

    Relay::Calling::DetectAction - The action object to interact with.

    Examples

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

    action = call.detect_digit!(digits: "345", timeout: 10)
    sleep 5
    action.stop
    

    detect_fax

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

    Available In:

    Parameters

    tone String optional The tone to detect: CED or CNG.
    Defaults to "CED".
    timeout Numeric optional Number of seconds to run the detector.
    Defaults to 30.0s.

    Returns

    Relay::Calling::DetectResult - The result object to interact with.

    Examples

    Detect fax on the current call.

    result = call.detect_fax
    puts "fax detected" if result.successful
    

    detect_fax!

    Asynchronous version of detect_fax. It does not wait for the detector to end, and returns a DetectAction object you can interact with.

    Available In:

    Parameters

    See detect_fax for the parameter list.

    Returns

    Relay::Calling::DetectAction - The action object to interact with.

    Examples

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

    action = call.detect_fax!
    sleep 5
    action.stop
    

    detect_human

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

    This method is DEPRECATED and will be removed in version 3.0

    Available In:

    Parameters

    params Hash optional Parameters to tune the detector. See detect parameters for the properties of params.
    timeout Numeric optional Number of seconds to run the detector.
    Defaults to 30.0s.

    Returns

    Relay::Calling::DetectResult - The result object to interact with.

    Examples

    Detect a human on the current call.

    result = call.detect_human
    puts "human detected" if result.successful
    

    detect_human!

    Asynchronous version of detect_human. It does not wait for the detector to end, and returns a DetectAction object you can interact with.

    This method is DEPRECATED and will be removed in version 3.0

    Available In:

    Parameters

    See detect_human for the parameter list.

    Returns

    Relay::Calling::DetectAction - The action object to interact with.

    Examples

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

    action = call.detect_human!
    sleep 5
    action.stop
    

    detect_machine

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

    This method is DEPRECATED and will be removed in version 3.0

    Available In:

    Parameters

    params Hash optional Parameters to tune the detector. See detect parameters for the properties of params.
    timeout Numeric optional Number of seconds to run the detector.
    Defaults to 30.0s.

    Returns

    Relay::Calling::DetectResult - The result object to interact with.

    Examples

    Detect a machine on the current call.

    result = call.detect_machine
    puts "machine detected" if result.successful
    

    detect_machine!

    Asynchronous version of detect_machine. It does not wait for the detector, and returns a DetectAction object you can interact with.

    This method is DEPRECATED and will be removed in version 3.0

    Available In:

    Parameters

    See detect_machine for the parameter list.

    Returns

    Relay::Calling::DetectAction - The action object to interact with.

    Examples

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

    action = call.detect_machine!
    sleep 5
    action.stop
    

    dial

    This will start a call that was created with new_call and wait until the call has been answered or hung up.

    Available In:

    Parameters

    None

    Returns

    Relay::Calling::DialResult - The result object to interact with.

    Examples

    call = client.calling.new_call(from: "+1XXXXXXXXXX", to: "+1YYYYYYYYYY")
    call.dial
    

    fax_receive

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

    Available In:

    Parameters

    None

    Returns

    Relay::Calling::FaxResult - The result object to interact with.

    Examples

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

    fax_result = call.fax_receive
    logger.debug "Received a fax: #{fax_result.document} that is #{fax_result.pages} pages long."
    

    fax_receive!

    Asynchronous version of fax_receive. It does not block until the fax is received, it immediately returns a FaxAction object you can interact with.

    Available In:

    Parameters

    None

    Returns

    Relay::Calling::FaxAction - The action object to interact with.

    Examples

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

    fax_action = call.fax_receive!
    sleep 5
    fax_action.stop
    

    fax_send

    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

    Relay::Calling::FaxResult - The result object to interact with.

    Examples

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

    fax_result = call.fax_send(document: "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf")
    logger.debug "Sent a fax: #{fax_result.document} that is #{fax_result.pages} pages long."
    

    fax_send!

    Asynchronous version of fax_send. It does not block until the fax is finished sending, it immediately returns a FaxAction object you can interact with.

    Available In:

    Parameters

    See fax_send for the parameter list.

    Returns

    Relay.Calling.FaxAction - The action object to interact with.

    Examples

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

    fax_action = call.fax_send(document: "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf")
    sleep 5
    fax_action.stop
    

    hangup

    Hangup the call.

    Available In:

    Parameters

    None

    Returns

    Relay::Calling::HangupResult - The result object to interact with.

    Examples

    Hangup a call and check if it was successful.

    hangup_result = call.hangup
    if hangup_result.successful
      # call was hung up correctly
    end
    

    on

    Attach an event handler for various events.

    Available In:

    Parameters

    event Symbol required Event name. Full list of events Relay::Calling::Call Events
    handler Proc 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 do |event|
       # call was answered by event
    end
    
    call.on :ended do |event|
       # call ended on event
    end
    

    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 play_audio, play_silence, play_tts or playRingtone for more specific usage.

    Available In:

    Parameters

    media1, media2, ..mediaN Array required One or more objects with the following structure:
    volume Numeric optional Volume setting. See PlayAction::volume for details
    • To play an audio file:

      type String required audio
      params Hash required Parameters to specify the played audio:
      params.url String required Http(s) URL to audio resource to play.
    • To play a text to speech string:

      type String required tts
      params Hash required Parameters for the TTS playback:
      params.text String required Text to speech string to play.
      params.language String optional Default to en-US.
      params.gender String optional male or female. Default to female.
    • To play silence:

      type String required silence
      params Hash required Parameters for silence:
      params.duration Numeric required Seconds of silence to play.
    • To play a ringtone:

      type String required ringtone
      name String required The name of the ringtone. See ringtones for the supported values.
      duration Numeric optional Duration of ringtone to play.
      Defaults to 1 ringtone iteration.

    Returns

    Relay::Calling::PlayResult - The result object to interact with.

    Examples

    Play multiple media elements in the call.

    media = [
      { type: 'tts', params: { text: 'Listen this awesome file!' } },
      { type: 'audio', params: { url: 'https://cdn.signalwire.com/default-music/welcome.mp3' } },
      { type: 'silence', params: { duration: 5 } },
      { type: 'tts', params: { text: 'Did you like it?' } }
    ]
    
    play_result = call.play media
    

    play!

    Asynchronous version of play. It does not wait for the playing event to complete, it immediately returns a PlayAction object you can interact with.

    Available In:

    Parameters

    See play for the parameter list.

    Returns

    Relay::Calling::PlayAction - The action object to interact with.

    Examples

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

    media = [
      { type: 'tts', params: { text: 'Listen this awesome file!' } },
      { type: 'audio', params: { url: 'https://cdn.signalwire.com/default-music/welcome.mp3' } },
      { type: 'silence', params: { duration: 5 } },
      { type: 'tts', params: { text: 'Did you like it?' } }
    ]
    
    play_action = call.play media
    
    sleep 2
    play_action.stop # audio will stop after 2 seconds
    

    play_audio

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

    Available In:

    Parameters

    url String required Http(s) URL to audio resource to play.
    volume Numeric optional Volume setting. See PlayAction::volume for details

    Returns

    Relay::Calling::PlayResult - The result object to interact with.

    Examples

    Play an MP3 file.

    call.play_audio('https://cdn.signalwire.com/default-music/welcome.mp3')
    

    play_audio!

    Asynchronous version of play_audio. It does not wait for the playing event to complete, and immediately returns a PlayAction object you can interact with.

    Available In:

    Parameters

    See play_audio for the parameter list.

    Returns

    Relay::Calling::PlayAction - The action object to interact with.

    Examples

    Play an MP3 file and stop it after 2 seconds.

    play_action = call.play_audio!('https://cdn.signalwire.com/default-music/welcome.mp3')
    sleep 2
    play_action.stop # audio will stop after 2 seconds
    

    play_ringtone

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

    Available In:

    Parameters

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

    Returns

    Relay::Calling::PlayResult - The result object to interact with.

    Examples

    Play a single US ringtone. ruby result = call.play_ringtone(name: 'US')

    playRingtoneAsync

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

    Available In:

    Parameters

    See play_ringtone for the parameter list.

    Returns

    Relay::Calling::PlayAction - The action object to interact with.

    Examples

    Play US ringtone for 30 seconds and stop it after 5 seconds. ruby result = call.play_ringtone!(name: 'US', duration: 30) sleep(5) result.stop

    play_silence

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

    Available In:

    Parameters

    duration Numeric required Seconds of silence to play.

    Returns

    Relay::Calling::PlayResult - The result object to interact with.

    Examples

    Play silence for 10 seconds.

    result = call.play_silence(10)
    

    play_silence!

    Asynchronous version of play_silence. It does not wait for the playing event to complete, it immediately returns a PlayAction object you can interact with.

    Available In:

    Parameters

    See play_silence for the parameter list.

    Returns

    Relay::Calling::PlayAction - The action object to interact with.

    Examples

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

    action = call.play_silence(60)
    action.stop if Agent.available
    

    play_tts

    This is a helper function that refines the use of play. This simplifies playing text to speach strings.

    Available In:

    Parameters

    sentence String required TTS to play.
    language String optional Default to en-US.
    gender String optional male or female. Default to female.
    volume Numeric optional Volume setting. See PlayAction::volume for details

    Returns

    Relay::Calling::PlayResult - The result object to interact with.

    Examples

    Play text to string.

    result = call.play_tts text: "the quick brown fox jumps over the lazy dog", language: "en-US", gender: "male"
    

    play_tts!

    Asynchronous version of play_tts. It does not wait for the playing event to complete, it immediately returns a PlayAction object you can interact with.

    Available In:

    Parameters

    See play_tts for the parameter list.

    Returns

    Relay::Calling::PlayAction - The action object to interact with.

    Examples

    Play TTS and stop it after 2 seconds.

    action = call.play_tts! text: "the quick brown fox jumps over the lazy dog", language: "en-US", gender: "male"
    sleep 2
    action.stop
    

    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 succeeds or a timeout is reached.

    The prompt method is a generic method, see prompt_audio or prompt_tts for more specific usage.

    Passing any of the digits_ or speech_ arguments will activate the respective detector.

    Available In:

    Parameters

    initial_timeout Numeric Timeout in seconds.
    partial_results Boolean Whether to return partial results during detection. Defaults to false.
    digits_max Numeric < Max digits to collect.
    digits_timeout Numeric Timeout in seconds between each digit.
    digits_terminators String optional DTMF digits that will end the recording.
    Default not set.
    speech_timeout Numeric optional How much silence to wait for end of speech.
    Default 1 second.
    speech_language String optional Language to detect.
    Default to en-US.
    speech_hints array optional Array of expected phrases to detect.
    play ... playN Hash required One or more Media objects with the same structure used in play
    volume Numeric optional Volume setting. See PlayAction::volume for details

    Returns

    Relay::Calling::PromptResult - The result object to interact with.

    Examples

    Ask user to enter their PIN and collect the digits.

    tts = [{ type: 'tts', params: { text: 'Please, enter your 3 digit PIN.' } }]
    result = call.prompt(initial_timeout: 10, digits_max: 3, digits_timeout: 5, play: tts)
    
    if result.successful)
      type = result.type # digit
      pin = result.result # pin entered by the user
    end
    

    prompt!

    Asynchronous version of prompt. It does not wait for the collect action to complete, it immediately returns a PromptAction object you can interact with.

    Available In:

    Parameters

    See prompt for the parameter list.

    Returns

    Relay::Calling::PromptAction - The action object to interact with.

    Examples

    Ask user to enter their PIN and collect the digits.

    tts = [{ type: 'tts', params: { text: 'Please, enter your 3 digit PIN.' } }]
    action = call.prompt!(initial_timeout: 10, digits_max: 3, digits_timeout: 5, play: tts)
    
    # .. do other important things while collecting user digits..
    
    if action.completed)
      result = action.result # => PromptResult object
    end
    
    main().catch(console.error)
    

    prompt_audio

    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

    See prompt for the parameter list, plus:

    url String required Http(s) URL to audio resource to play.
    volume Numeric optional Volume setting. See PlayAction::volume for details

    Returns

    Relay::Calling::PromptResult - The result object to interact with.

    Examples

    Collect user's digits while playing an MP3 file, setting its volume to 20.

    result = call.prompt_audio(initial_timeout: 10, digits_max: 3, digits_timeout: 5, url: 'https://cdn.signalwire.com/default-music/welcome.mp3', volume: 20)
    
    if result.successful
      type = promptResult.type # digit
      digits = promptResult.result # digits entered by the user
    end
    

    prompt_audio!

    Asynchronous version of prompt_audio. It does not wait for the collect action to complete, it immediately returns a PromptAction object you can interact with.

    Available In:

    Parameters

    See prompt_audio for the parameter list.

    Returns

    Relay::Calling::PromptAction - The action object to interact with.

    Examples

    Ask user to enter their PIN and collect the digits.

    action = call.prompt_audio!(initial_timeout: 10, digits_max: 3, digits_timeout: 5, url: 'https://cdn.signalwire.com/default-music/welcome.mp3')
    
    # .. do other important things while collecting user digits..
    
    if action.completed
        result = action.result # => PromptResult object
    end
    

    prompt_silence

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

    Available In:

    Parameters

    See prompt for the parameter list, plus:

    duration Numeric required Seconds of silence to play.

    Returns

    Relay::Calling::PromptResult - The result object to interact with.

    Examples

    Collect user's digits while playing 5 seconds of silence.

    result = call.prompt_silence(initial_timeout: 10, digits_max: 3, digits_timeout: 5, duration: 5)
    
    if result.successful
      type = promptResult.type # digit
      digits = promptResult.result # digits entered by the user
    end
    

    prompt_silence!

    Asynchronous version of prompt_silence. It does not wait for the collect action to complete, it immediately returns a PromptAction object you can interact with.

    Available In:

    Parameters

    See prompt_silence for the parameter list.

    Returns

    Relay::Calling::PromptAction - The action object to interact with.

    Examples

    Collect user's digits while playing 5 seconds of silence.

    action = call.prompt_silence!(initial_timeout: 10, digits_max: 3, digits_timeout: 5, duration: 5)
    
    # .. do other important things while collecting user digits..
    
    if action.completed
        result = action.result # => PromptResult object
    end
    

    prompt_ringtone

    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

    See prompt for the parameter list, plus:

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

    Returns

    Relay::Calling::PromptResult - The result object to interact with.

    Examples

    Play US ringtone for 30 seconds while collecting digits.

    result = call.prompt_ringtone(name: 'us', duration: 30, digits_max: 3)
    
    if result.successful
      type = promptResult.type # digit
      digits = promptResult.result # digits entered by the user
    end
    

    prompt_ringtone!

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

    Available In:

    Parameters

    See prompt_ringtone for the parameter list.

    Returns

    Relay::Calling::PromptAction - The action object to interact with.

    Examples

    Play US ringtone for 30 seconds while collecting digits in asynchronous mode.

    result = call.prompt_ringtone!(name: 'us', duration: 30, digits_max: 3)
    
    # code is executing here...
    
    if result.successful
      type = promptResult.type # digit
      digits = promptResult.result # digits entered by the user
    end
    

    prompt_tts

    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

    See prompt for the parameter list, plus:

    text String required TTS to play.
    language String optional Default to en-US.
    gender String optional male or female. Default to female.
    volume Numeric optional Volume setting. See PlayAction::volume for details

    Returns

    Relay::Calling::PromptResult - The result object to interact with.

    Examples

    Ask user to enter their PIN and collect the digits.

    result = call.prompt_tts initial_timeout: 10, digits_max: 3, digits_timeout: 5, text: 'Please, enter your 3 digit PIN.', gender: 'male'
    
    if result.successful
      type = promptResult.type # digit
      digits = promptResult.result # digits entered by the user
    end
    

    prompt_tts!

    Asynchronous version of prompt_tts. It does not wait for the collection event to complete, it immediately returns a PromptAction object you can interact with.

    Available In:

    Parameters

    See prompt_tts for the parameter list.

    Returns

    Relay::Calling::PromptAction - The action object to interact with.

    Examples

    Ask user to enter their PIN and collect the digits.

    action = call.prompt_tts! initial_timeout: 10, digits_max: 3, digits_timeout: 5, text: 'Please, enter your 3 digit PIN.', gender: 'male'
    
    # .. do other important things while collecting user digits..
    
    if action.completed
        result = action.result # => PromptResult object
    end
    

    record

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

    Available In:

    Parameters

    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 / both. Default to speak.
    initial_timeout Numeric optional How long to wait in seconds until something is heard in the recording. Disable with 0.
    Default 5.0.
    end_silence_timeout Numeric 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

    Relay::Calling::RecordResult - The result object to interact with.

    Examples

    Start recording audio in the call for both direction in stereo mode, if successful, print the url from the RecordResult object.

    result = call.record(stereo: true, direction: 'both')
    
    if result.successful
      puts result.url # the HTTP URL of the recording
    end
    

    record!

    Asynchronous version of record. It does not wait for the end of the recording, it immediately returns a RecordAction object you can interact with.

    Available In:

    Parameters

    See record for the parameter list.

    Returns

    Relay::Calling::RecordAction - The action object to interact with.

    Examples

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

    action = call.record!(stereo: true, direction: 'both')
    sleep 2
    action.stop
    

    send_digits

    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 or wW for short and long waits. If any invalid characters are present, the entire operation is rejected.

    Returns

    Relay::Calling::SendDigitsResult - The result object to interact with.

    Examples

    Send some digits.

    call.send_digits('123')
    

    send_digits!

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

    Available In:

    Parameters

    See send_digits for the parameter list.

    Returns

    Relay::Calling::SendDigitsAction - The action object to interact with.

    Examples

    Send some digits bu.

    action = call.send_digits!('123123123123123')
    # Do something while digits are sending...
    

    tap_media

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

    This method is named tap_media instead of tap in the Ruby SDK because of a reserved method.

    Available In:

    Parameters

    audio_direction String optional listen to tap what the caller hears, speak for what the caller says or both.
    Default speak.
    codec String optional Optional codec, `[OPUS
    target_addr String required RTP IP v4 address.
    target_port Numeric required RTP port.
    target_ptime Numeric optional Optional packetization time in ms. It will be the same as the tapped audio if not set.

    Returns

    Relay::Calling::TapResult - The result object to interact with.

    Examples

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

    result = call.tap_media(audio_direction: "listen", target_addr: "127.0.0.1", target_port: 1234)
    
    if result.successful)
      puts result.source_device
      puts result.destination_device
    end
    

    tap_media!

    Asynchronous version of tap_media. It does not wait the end of tapping but returns a TapAction object you can interact with.

    Available In:

    Parameters

    See tap_media for the parameter list.

    Returns

    Relay::Calling::TapAction - The action object to interact with.

    Examples

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

    action = call.tap_media!(audio_direction: "listen", target_addr: "127.0.0.1", target_port: 1234)
    sleep 5
    action.stop
    

    wait_for

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

    Available In:

    Parameters

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

    Returns

    Boolean - true/false.

    Examples

    Wait for ending or ended events.

    if call.wait_for('ending', 'ended')
      # ending or ended was received
    end
    

    wait_for_answered

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

    Available In:

    Parameters

    None

    Returns

    Boolean - true/false.

    Examples

    Wait for the answered event.

    if call.wait_for_answered
      # answered was received
    end
    

    wait_for_ended

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

    Available In:

    Parameters

    None

    Returns

    Boolean - true/false.

    Examples

    Wait for the ended event.

    if call.wait_for_ended
      # ended was received
    end
    

    wait_for_ending

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

    Available In:

    Parameters

    None

    Returns

    Boolean - true/false.

    Examples

    Wait for the ending event.

    if call.wait_for_ending
      # ending was received
    end
    

    wait_for_ringing

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

    Available In:

    Parameters

    None

    Returns

    Boolean - true/false.

    Examples

    Wait for the ringing event.

    if call.wait_for_ringing
      # ringing was received
    end
    

    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.

    state_change 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_state_hange 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.

    Prompt Events

    To track a prompt state.

    prompt The prompt action on the call has ended.

    Ringtones

    Here you can find all the accepted values for playing a ringtone, 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 is returned by connect! method and 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 Hash Payload sent to Relay to start the connect.

    stop

    Stop the action immediately.

    Available In:

    Parameters

    None

    Returns

    Relay::Calling::StopResult - A StopResult object with a successful property.

    Relay::Calling::ConnectResult

    This object is returned by the connect method and 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 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

    Relay::Calling::StopResult - A StopResult object with a successful property.

    Examples

    Detect a machine on the current call. Stop the action after 5 seconds. ruby action = call.detect!(type: :machine) sleep 5 action.stop

    Relay::Calling::DetectResult

    This object is returned by detect method and represents the final result of a detect attempt.

    Properties

    successful Boolean Whether the detection attempt succeeded.
    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 is returned by the 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 the asynchronous fax_send! and fax_receive! methods that 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 Hash 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

    Relay::Calling::StopResult - A StopResult object with a successful property.

    Relay::Calling:::FaxResult

    This object is returned from the fax_send and fax_receive method and 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 Numeric Number of sent/received pages.

    Relay::Calling::HangupResult

    This object is returned by the 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 is returned by the asynchronous play! family of methods and represents a playing action that is 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 Hash Payload sent to Relay to start playing.
    control_id String UUID to identify the playing.

    Methods

    stop

    Stop the action immediately.

    Available In:

    Parameters

    None

    Returns

    Relay::Calling::StopResult - A StopResult object with a successful property.

    pause

    Pause the playback immediately.

    Available In:

    Parameters

    None

    Returns

    Relay::Calling::PlayPauseResult - A PlayPauseResult object with a successful property.

    Examples

    Play some audio and pause after 2 seconds.

    play_action = call.play_audio('https://cdn.signalwire.com/default-music/welcome.mp3')
    
    sleep 2
    result = play_action.pause
    
    puts "Pause was successful" if result.successful
    

    resume

    Resume the playback immediately.

    Available In:

    Parameters

    None

    Returns

    Relay::Calling::PlayResumeResult - A PlayResumeResult object with a successful property.

    Examples

    Play some audio and pause after 2 seconds, then resume playing after 2 more seconds

    play_action = call.play_audio('https://cdn.signalwire.com/default-music/welcome.mp3')
    
    sleep 2
    play_action.pause
    sleep 2
    result = play_action.resume
    
    puts "Resume was successful" if result.successful
    

    volume

    Sets the volume for the playback.

    Uses a value from -40dB to +40dB where 0 is original audio and -40 is muted. It follows the standard amplitude voltage gain factor: 10 pow (value / 20).

    Available In:

    Parameters | | | | | -: | - | - | | setting | Numeric | required | Volume setting |

    Returns

    Relay::Calling::PlayVolumeResult - A PlayVolumeResult object with a successful property.

    Examples

    Play some audio and change the volume

    play_action = call.play_audio('https://cdn.signalwire.com/default-music/welcome.mp3')
    
    result = play_action.volume 20
    
    puts "Volume change was successful" if result.successful
    

    Relay::Calling::PlayResult

    This object is returned by the play methods and represents the final result of a playing action.

    Properties

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

    Relay::Calling::PlayPauseResult

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

    Properties

    successful Boolean Whether playback has been paused successfully.

    Relay::Calling::PlayResumeResult

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

    Properties

    successful Boolean Whether playback has resumed successfully.

    Relay::Calling::PlayVolumeResult

    This object is returned by volume method and represents the result of setting the volume.

    Properties

    successful Boolean Whether volume has been set successfully.

    Relay::Calling::PromptAction

    This object returned from the asynchronous prompt! family of methods and is the handle for 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 Hash 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

    Relay::Calling::StopResult - A StopResult object with a successful property.

    volume

    Sets the volume for the prompt playback.

    Uses a value from -40dB to +40dB where 0 is original audio and -40 is muted. It follows the standard amplitude voltage gain factor: 10 pow (value / 20).

    Available In:

    Parameters | | | | | -: | - | - | | setting | Numeric | required | Volume setting |

    Returns

    Relay::Calling::PromptVolumeResult - A PromptVolumeResult object with a successful property.

    Examples

    Play some prompt and change the volume

    prompt_action = call.prompt_audio(initial_timeout: 10, digits_max: 3, digits_timeout: 5, url: 'https://cdn.signalwire.com/default-music/welcome.mp3')
    
    result = prompt_action.volume 20
    
    puts "Volume change was successful" if result.successful
    

    Relay::Calling::PromptResult

    This object is returned by the prompt group of methods and 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 Numeric Confidence of the result on a speech prompt.

    Relay::Calling::PromptVolumeResult

    This object is returned by volume method and represents the result of setting the volume.

    Properties

    successful Boolean Whether volume has been set successfully.

    Relay::Calling::RecordAction

    This object is returned by the record! method and represents a recording that is currently active on a call.

    Properties

    result Relay::Calling::RecordResult Final result of recording.
    state String Current state of recording.
    completed Boolean Whether the recording has finished.
    payload Hash Payload sent to Relay to start recording.
    controlId String UUID to identify the recording.
    url String Url of the recording. The file may not be present until the recording is finished.

    Methods

    stop

    Stop the action immediately.

    Available In:

    Parameters

    None

    Returns

    Relay::Calling::StopResult - A StopResult object with a successful property.

    Relay::Calling::RecordResult

    This object is returned by the record method and 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 Numeric Duration of the recording in seconds.
    size Numeric Size of the recording.

    Relay::Calling::SendDigitsAction

    This object is returned by the asynchronous send_digits! method and represents a send_digits action that is currently active on a call.

    Properties

    result Relay::Calling::SendDigitsResult Final result of sending digits.
    state String Current state of the digits being sent.
    completed Boolean Whether the sending has finished.
    control_id String UUID to identify the action.

    Relay::Calling::SendDigitsResult

    This object is returned by the send_digits methods and represents the final result of an action sending digits.

    Properties

    successful Boolean Whether the action has completed successfully.
    event Relay::Event Last event that completed the action.

    Relay::Calling:::StopResult

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

    Available In:

    Properties

    successful Boolean Whether the stop action has been performed successfully.

    Relay::Calling::TapAction

    This object returned by the asynchronous See tap_media! for the parameter list. method that represents a running media tap on the call.

    Properties

    result Relay::Calling::DetectResult Final tap result.
    completed Boolean Whether the action has finished.
    payload Hash Payload sent to Relay to start tapping.
    control_Id String UUID to identify the action.
    source_device Hash Source device sending media.

    Methods

    stop

    Stop the action immediately.

    Available In:

    Parameters

    None

    Returns

    Relay::Calling::StopResult - A StopResult object with a successful property.

    Examples

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

    action = call.tap_media!(audio_direction: "listen", target_addr: "127.0.0.1", target_port: 1234)
    sleep 5
    action.stop
    

    Relay::Calling::TapResult

    This object is returned by tap_media method and represents the final result of a tap attempt.

    Properties

    successful Boolean Whether the call has been connected successfully.
    event Relay::Event Last event that completed the operation.
    tap_media Hash Object with payload for this tap_media action.
    sourceDevice Hash Source device sending media.
    destinationDevice Hash Destination device receiving media.

    Relay::Consumer

    A Relay Consumer is a simple 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 buisness 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.

    Authenticating a consumer

    Authentication requires a SignalWire project ID and a token. You can generate one from your dashboard.

    The values can be passed in either as the project and token parameters to the constructor, or by setting the SIGNALWIRE_PROJECT_KEY and SIGNALWIRE_TOKEN environment variables.

    An example using constructor parameters:

    class MyConsumer < Signalwire::Relay::Consumer
      contexts ['incoming']
    
      def on_incoming_call(call)
        call.answer
        call.play_tts 'this consumer uses constructor parameters'
    
        call.hangup
      end
    end
    
    MyConsumer.new(project: 'your-project-key', token: 'your-project-token').run
    

    Consumer Contexts

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

    A consumer usually requires at least one contexts for incoming events. Contexts are a list of contexts you want this Consumer to listen for. Learn more about Contexts.

    class MyConsumer < Signalwire::Relay::Consumer
      contexts ['incoming']
    
      def on_incoming_call(call)
        call.answer
        call.play_tts 'the quick brown fox jumps over the lazy dog'
    
        call.hangup
      end
    end
    
    MyConsumer.new.run
    

    Initializing Consumers

    You can optionally define a 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.

    class MyConsumer < Signalwire::Relay::Consumer
      contexts ['incoming']
    
      def setup
        SomeDatabase.connect
      end
    
      def on_incoming_call(call)
        call.answer
        call.play_tts 'the quick brown fox jumps over the lazy dog'
    
        call.hangup
      end
    end
    
    MyConsumer.new.run
    

    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.

    on_incoming_call

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

    Available In:

    class MyConsumer < Signalwire::Relay::Consumer
      contexts ['incoming']
    
      def on_incoming_call(call)
        call.answer
        call.play_tts 'the quick brown fox jumps over the lazy dog'
    
        call.hangup
      end
    end
    
    MyConsumer.new.run
    

    ready

    This method is executed when the Consumer has connected and is ready to make Relay requests.

    Available In:

    require 'signalwire'
    
    class MyConsumer < Signalwire::Relay::Consumer
      def ready
        logger.debug "The consumer is ready to execute actions now"
        # Send an SMS on ready
        result = client.messaging.send(from: "+1XXXXXXXXXX", to: "+1YYYYYYYYYY", context: 'incoming', body: 'Hello from SignalWire!')
        logger.debug "message id #{result.message_id} was successfully sent" if result.successful
      end
    end
    
    MyConsumer.new.run
    

    on_task

    Receives your message sent through a Relay::Task.

    Available In:

    require 'signalwire'
    
    class MyConsumer < Signalwire::Relay::Consumer
      contexts ['incoming']
    
      def on_task(task)
        logger.debug "Received #{task.message}"
      end
    end
    
    MyConsumer.new.run
    

    on_incoming_message

    This method is executed when the consumer receives an inbound text message on one of the subscribed contexts. Receives a Message object as a parameter.

    Available In:

    class MessageReceiveConsumer < Signalwire::Relay::Consumer
      contexts ['office']
    
      def on_incoming_message(message)
        logger.info "Received message from #{message.from}: #{message.body}"
      end
    end
    
    MessageReceiveConsumer.new.run
    

    on_message_state_change

    Executed when a message state changes in a context the consumer is subscribed to. Receives a Message object as a parameter.

    Available In:

    class MessageSendConsumer < Signalwire::Relay::Consumer
      def on_message_state_change(message)
        logger.debug "message id #{rmessage.id} now has state #{message.state}"
      end
    end
    
    MessageSendConsumer.new.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.

    class MyConsumer < Signalwire::Relay::Consumer
      contexts ['incoming']
    
      def teardown
        SomeDatabase.disconnect
      end
    
      def on_incoming_call(call)
        call.answer
        call.play_tts 'the quick brown fox jumps over the lazy dog'
    
        call.hangup
      end
    end
    
    MyConsumer.new.run
    

    Running Consumers

    Running a consumer is just like running any Ruby script, simply execute the script as a separate process and call run to start it. 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.

    Relay::Event

    Any Event emitted by Relay.

    Properties

    name String The event name.
    payload Hash Raw JSON object of the Relay event.

    Relay::Messaging

    This namespace represents the API interface for the Messaging Relay Service. It is used to send and receive text messages.

    Methods

    send

    Send an outbound SMS or MMS message.

    Available In:

    Parameters

    to String required The number you are attempting to send the message to.
    from String required The phone number to place the message from. Must be a SignalWire phone number or short code that you own.
    context String required The SignalWire context on which you will receive updates aboun the message state.
    body String optional The text body to send. Either body or media must be specified.
    media Array optional An array of media URLs to send with an MMS. Either body or media must be specified.
    tags Array optional An array of tags to tag the message with. For searching in the UI and identifying messages.

    Returns

    Signalwire::Relay::Messaging::SendResult - the result of the send command.

    Examples

    Send a message in the office context.

    result = client.messaging.send(
      from: '+1XXXXXXXXXX',
      to: '+1YYYYYYYYYY',
      context: 'office',
      body: 'SignalWire says hello!'
    )
    
    puts "Message #{result.message_id} was successfully sent" if result.successful
    

    Relay::Messaging::Message

    An object representing an SMS or MMS message. It is the parameter of both on_incoming_message and on_message_state_change 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 Array Array of URL media strings.
    tags Array Array of strings with message tags.
    segments Numeric 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 initiated 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 message delivery has failed.

    Relay::Messaging::SendResult

    The send method returns an instance of this class, representing the result of a send operation.

    Properties

    successful Boolean Whether the send operation has successfully queued the message.
    message_id String The ID of the queued message.
    code String The Relay request code. 200 represents success.

    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.

    require 'signalwire/relay/task'
    
    task = Signalwire::Relay::Task.new(project: "your-project-id", token: "your-project-token")
    task.deliver(context: 'incoming', message: { number_to_call: '+1555XXXXXXX', message_to_play: 'We have a message for you' })
    

    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 Hash required Object with your custom data that will be sent to your Consumer's on_task handler.

    Returns

    Booelan - true if the request was successful, false if not.

    Examples

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

    message = {
      'action': 'call',
      'from': '+18881112222'
      'to': '+18881113333'
    }
    
    result = task.deliver(context: 'incoming', message: message)
    
    puts "error delivering task" if result == false