Conference & Broadcast with Ruby and Rails

January 10, 2017
Written by
Reviewed by
Paul Kamp
Twilion
Kat King
Twilion
Jose Oliveros
Contributor
Opinions expressed by Twilio contributors are their own

conference-broadcast-ruby

This Ruby on Rails sample application is inspired by the Rapid Response Kit, built by Twilio and used all over the world by organizations who need to act quickly in disastrous situations.

Aid workers can use the tools in this app to communicate immediately with a large group of volunteers. In situations where all parties need to talk at once the organizer can quickly spin up a conference line. In other situations she can broadcast a spoken message to a list of volunteer phone numbers.

To run this sample app yourself, download the code and follow the instructions on GitHub. You might also want to click around the views for this app, since in this tutorial we will only be covering the Twilio pieces.

Create a Conference Number

Before we can call our conference line we need to configure one of our Twilio numbers to send our web application an HTTP request when we get an incoming call.

Click on one of your numbers and configure the Voice URL to point to our app. In our code the route will be /Conference/Join

Twilio Console configured for Conference Broadcast

Create a Simple Conference Call

Our Twilio number is now configured to send HTTP requests to this controller method on any incoming voice calls. Our app responds with TwiML to tell Twilio how to handle the call.

We use the Twilio Ruby library to generate some TwiML that tells Twilio to Dial into a Conference that we're naming RapidResponseRoom. This means that anyone who calls your Twilio number will automatically join this conference.

Editor: this is a migrated tutorial. Clone the original from https://github.com/TwilioDevEd/conference-broadcast-rails/

class TwilioController < ApplicationController
  TWILIO_API_HOST = 'https://api.twilio.com'

  before_action :set_client_and_number, only: [:start_call_record, :broadcast_send, :fetch_recordings, :conference]

  # GET /conference
  def conference
    @conference_number = @twilio_number
  end

  # POST /conference
  def join_conference
    response = Twilio::TwiML::VoiceResponse.new
    response.say("You are about to join the Rapid Response conference")
    gather = Twilio::TwiML::Gather.new(action: 'conference/connect')
    gather.say("Press 1 to join as a listener.")
    gather.say("Press 2 to join as a speaker.")
    gather.say("Press 3 to join as the moderator.")
    response.append(gather)

    render xml: response.to_s
  end

  # POST /conference/connect
  def conference_connect
    case params['Digits']
    when "1" # listener
      @muted = "true"
    when "3" # moderator
      @moderator = "true"
    end

    response = Twilio::TwiML::VoiceResponse.new
    response.say("You have joined the conference.")
    dial = Twilio::TwiML::Dial.new
    dial.conference("RapidResponseRoom",
      wait_url: "http://twimlets.com/holdmusic?Bucket=com.twilio.music.ambient",
      muted: @muted || "false",
      start_conference_on_enter: @moderator || "false",
      endConference_on_exit: @moderator || "false")
    response.append(dial)

    render xml: response.to_s
  end

  # POST /broadcast/record
  def broadcast_record
    response = Twilio::TwiML::VoiceResponse.new
    response.say("Please record your message after the beep. Press star to end your recording.")
    response.record(finish_on_key: "*")

    render xml: response.to_s
  end

  # POST /broadcast/send
  def broadcast_send
    numbers = CSV.parse(params[:numbers])
    recording = params[:recording_url]
    url = request.base_url + '/broadcast/play?recording_url=' + recording

    numbers.each do |number|
      @client.calls.create(
        from: @twilio_number,
        to: number,
        url: url
      )
    end
  end

  # POST /broadcast/play
  def broadcast_play
    recording_url = params[:recording_url]
    response = Twilio::TwiML::VoiceResponse.new
    response.play(recording_url)

    render xml: response.to_s
  end

  # GET /broadcast
  def broadcast
  end

  # POST /call_recording
  def start_call_record
    phone_number = params[:phone_number]

    @client.calls.create(
      from: @twilio_number,
      to: phone_number,
      url: "#{request.base_url}/broadcast/record"
    )
  end

  # GET /fetch_recordings
  def fetch_recordings
    recordings = @client.recordings.list.map do |recording|
      {
        url:  full_recording_uri(recording.uri),
        date: recording.date_created
      }
    end

    render json: recordings
  end

  private

  # returns full uri given partial recording uri
  def full_recording_uri(uri)
    # remove json extension from uri
    clean_uri = uri.sub!('.json', '')

    "#{TWILIO_API_HOST}#{clean_uri}"
  end

  def set_client_and_number
    @client = Twilio::REST::Client.new ENV['TWILIO_ACCOUNT_SID'], ENV['TWILIO_AUTH_TOKEN']
    @twilio_number = ENV['TWILIO_NUMBER']
  end
end

Next we'll turn this into a moderated conference line, with a moderator and listeners.

Create a Moderated Conference

In this scenario we ask for the caller's role before we connect them to the conference. These roles are:

  • Moderator: can start and end the conference
  • Speaker: can speak on the conference call
  • Listener: is muted and can only listen to the call

In this controller we Say a simple message and then ask the caller to choose a role.

class TwilioController < ApplicationController
  TWILIO_API_HOST = 'https://api.twilio.com'

  before_action :set_client_and_number, only: [:start_call_record, :broadcast_send, :fetch_recordings, :conference]

  # GET /conference
  def conference
    @conference_number = @twilio_number
  end

  # POST /conference
  def join_conference
    response = Twilio::TwiML::VoiceResponse.new
    response.say("You are about to join the Rapid Response conference")
    gather = Twilio::TwiML::Gather.new(action: 'conference/connect')
    gather.say("Press 1 to join as a listener.")
    gather.say("Press 2 to join as a speaker.")
    gather.say("Press 3 to join as the moderator.")
    response.append(gather)

    render xml: response.to_s
  end

  # POST /conference/connect
  def conference_connect
    case params['Digits']
    when "1" # listener
      @muted = "true"
    when "3" # moderator
      @moderator = "true"
    end

    response = Twilio::TwiML::VoiceResponse.new
    response.say("You have joined the conference.")
    dial = Twilio::TwiML::Dial.new
    dial.conference("RapidResponseRoom",
      wait_url: "http://twimlets.com/holdmusic?Bucket=com.twilio.music.ambient",
      muted: @muted || "false",
      start_conference_on_enter: @moderator || "false",
      endConference_on_exit: @moderator || "false")
    response.append(dial)

    render xml: response.to_s
  end

  # POST /broadcast/record
  def broadcast_record
    response = Twilio::TwiML::VoiceResponse.new
    response.say("Please record your message after the beep. Press star to end your recording.")
    response.record(finish_on_key: "*")

    render xml: response.to_s
  end

  # POST /broadcast/send
  def broadcast_send
    numbers = CSV.parse(params[:numbers])
    recording = params[:recording_url]
    url = request.base_url + '/broadcast/play?recording_url=' + recording

    numbers.each do |number|
      @client.calls.create(
        from: @twilio_number,
        to: number,
        url: url
      )
    end
  end

  # POST /broadcast/play
  def broadcast_play
    recording_url = params[:recording_url]
    response = Twilio::TwiML::VoiceResponse.new
    response.play(recording_url)

    render xml: response.to_s
  end

  # GET /broadcast
  def broadcast
  end

  # POST /call_recording
  def start_call_record
    phone_number = params[:phone_number]

    @client.calls.create(
      from: @twilio_number,
      to: phone_number,
      url: "#{request.base_url}/broadcast/record"
    )
  end

  # GET /fetch_recordings
  def fetch_recordings
    recordings = @client.recordings.list.map do |recording|
      {
        url:  full_recording_uri(recording.uri),
        date: recording.date_created
      }
    end

    render json: recordings
  end

  private

  # returns full uri given partial recording uri
  def full_recording_uri(uri)
    # remove json extension from uri
    clean_uri = uri.sub!('.json', '')

    "#{TWILIO_API_HOST}#{clean_uri}"
  end

  def set_client_and_number
    @client = Twilio::REST::Client.new ENV['TWILIO_ACCOUNT_SID'], ENV['TWILIO_AUTH_TOKEN']
    @twilio_number = ENV['TWILIO_NUMBER']
  end
end

So our callers have listened to a few role options they can choose from, and next they will choose one. For this we tell Twilio to Gather a button press from the caller's phone so we know which role they want to use. Let's see how next.

Connect to a Moderated Conference

The <Gather> verb from the previous step included an action parameter that took an absolute or relative URL as a value — in our case, the Conference/Connect route.

When the caller finishes entering digits Twilio makes a GET or POST request to this URL including a Digits parameter with the number our caller chose.

We use that parameter to set a couple variables, isMuted and canControlConferenceOnEnter, which we then use to configure our Dial and Conference TwiML elements.

class TwilioController < ApplicationController
  TWILIO_API_HOST = 'https://api.twilio.com'

  before_action :set_client_and_number, only: [:start_call_record, :broadcast_send, :fetch_recordings, :conference]

  # GET /conference
  def conference
    @conference_number = @twilio_number
  end

  # POST /conference
  def join_conference
    response = Twilio::TwiML::VoiceResponse.new
    response.say("You are about to join the Rapid Response conference")
    gather = Twilio::TwiML::Gather.new(action: 'conference/connect')
    gather.say("Press 1 to join as a listener.")
    gather.say("Press 2 to join as a speaker.")
    gather.say("Press 3 to join as the moderator.")
    response.append(gather)

    render xml: response.to_s
  end

  # POST /conference/connect
  def conference_connect
    case params['Digits']
    when "1" # listener
      @muted = "true"
    when "3" # moderator
      @moderator = "true"
    end

    response = Twilio::TwiML::VoiceResponse.new
    response.say("You have joined the conference.")
    dial = Twilio::TwiML::Dial.new
    dial.conference("RapidResponseRoom",
      wait_url: "http://twimlets.com/holdmusic?Bucket=com.twilio.music.ambient",
      muted: @muted || "false",
      start_conference_on_enter: @moderator || "false",
      endConference_on_exit: @moderator || "false")
    response.append(dial)

    render xml: response.to_s
  end

  # POST /broadcast/record
  def broadcast_record
    response = Twilio::TwiML::VoiceResponse.new
    response.say("Please record your message after the beep. Press star to end your recording.")
    response.record(finish_on_key: "*")

    render xml: response.to_s
  end

  # POST /broadcast/send
  def broadcast_send
    numbers = CSV.parse(params[:numbers])
    recording = params[:recording_url]
    url = request.base_url + '/broadcast/play?recording_url=' + recording

    numbers.each do |number|
      @client.calls.create(
        from: @twilio_number,
        to: number,
        url: url
      )
    end
  end

  # POST /broadcast/play
  def broadcast_play
    recording_url = params[:recording_url]
    response = Twilio::TwiML::VoiceResponse.new
    response.play(recording_url)

    render xml: response.to_s
  end

  # GET /broadcast
  def broadcast
  end

  # POST /call_recording
  def start_call_record
    phone_number = params[:phone_number]

    @client.calls.create(
      from: @twilio_number,
      to: phone_number,
      url: "#{request.base_url}/broadcast/record"
    )
  end

  # GET /fetch_recordings
  def fetch_recordings
    recordings = @client.recordings.list.map do |recording|
      {
        url:  full_recording_uri(recording.uri),
        date: recording.date_created
      }
    end

    render json: recordings
  end

  private

  # returns full uri given partial recording uri
  def full_recording_uri(uri)
    # remove json extension from uri
    clean_uri = uri.sub!('.json', '')

    "#{TWILIO_API_HOST}#{clean_uri}"
  end

  def set_client_and_number
    @client = Twilio::REST::Client.new ENV['TWILIO_ACCOUNT_SID'], ENV['TWILIO_AUTH_TOKEN']
    @twilio_number = ENV['TWILIO_NUMBER']
  end
end

That's it for connecting callers to our conference room. Let's explore next the other feature of this app: broadcasting a voice message to a list of phone numbers.

Voice Broadcast

In addition to hosting conference calls, an organizer can use our application to broadcast a voice message to a list of phone numbers. She can do this by choosing a recording from a dropdown, entering a list of phone numbers and clicking 'Submit'.

To power this feature, we'll use Twilio's REST API to fetch all of the recordings associated with our account. If our organizer wants to record a new message, we'll call her phone and record her response.

Now that we know what this feature is all about, let's take a dig into the code.

Fetch Recordings

This route fetches all of the recordings associated with our Twilio account. We could filter these results by date or call sid using Twilio's API, but for this example we just pull all recordings.

In order to use Twilio's handy API we need to first create our Twilio client, which we can easily do by passing our credentials. Since we are going to use @client a bit we will set it in a shared filter that is called before every action that needs it.

Once we get all of the recordings we need to render a JSON response of our recordings object. This route will be called by our Javascript on page load.

class TwilioController < ApplicationController
  TWILIO_API_HOST = 'https://api.twilio.com'

  before_action :set_client_and_number, only: [:start_call_record, :broadcast_send, :fetch_recordings, :conference]

  # GET /conference
  def conference
    @conference_number = @twilio_number
  end

  # POST /conference
  def join_conference
    response = Twilio::TwiML::VoiceResponse.new
    response.say("You are about to join the Rapid Response conference")
    gather = Twilio::TwiML::Gather.new(action: 'conference/connect')
    gather.say("Press 1 to join as a listener.")
    gather.say("Press 2 to join as a speaker.")
    gather.say("Press 3 to join as the moderator.")
    response.append(gather)

    render xml: response.to_s
  end

  # POST /conference/connect
  def conference_connect
    case params['Digits']
    when "1" # listener
      @muted = "true"
    when "3" # moderator
      @moderator = "true"
    end

    response = Twilio::TwiML::VoiceResponse.new
    response.say("You have joined the conference.")
    dial = Twilio::TwiML::Dial.new
    dial.conference("RapidResponseRoom",
      wait_url: "http://twimlets.com/holdmusic?Bucket=com.twilio.music.ambient",
      muted: @muted || "false",
      start_conference_on_enter: @moderator || "false",
      endConference_on_exit: @moderator || "false")
    response.append(dial)

    render xml: response.to_s
  end

  # POST /broadcast/record
  def broadcast_record
    response = Twilio::TwiML::VoiceResponse.new
    response.say("Please record your message after the beep. Press star to end your recording.")
    response.record(finish_on_key: "*")

    render xml: response.to_s
  end

  # POST /broadcast/send
  def broadcast_send
    numbers = CSV.parse(params[:numbers])
    recording = params[:recording_url]
    url = request.base_url + '/broadcast/play?recording_url=' + recording

    numbers.each do |number|
      @client.calls.create(
        from: @twilio_number,
        to: number,
        url: url
      )
    end
  end

  # POST /broadcast/play
  def broadcast_play
    recording_url = params[:recording_url]
    response = Twilio::TwiML::VoiceResponse.new
    response.play(recording_url)

    render xml: response.to_s
  end

  # GET /broadcast
  def broadcast
  end

  # POST /call_recording
  def start_call_record
    phone_number = params[:phone_number]

    @client.calls.create(
      from: @twilio_number,
      to: phone_number,
      url: "#{request.base_url}/broadcast/record"
    )
  end

  # GET /fetch_recordings
  def fetch_recordings
    recordings = @client.recordings.list.map do |recording|
      {
        url:  full_recording_uri(recording.uri),
        date: recording.date_created
      }
    end

    render json: recordings
  end

  private

  # returns full uri given partial recording uri
  def full_recording_uri(uri)
    # remove json extension from uri
    clean_uri = uri.sub!('.json', '')

    "#{TWILIO_API_HOST}#{clean_uri}"
  end

  def set_client_and_number
    @client = Twilio::REST::Client.new ENV['TWILIO_ACCOUNT_SID'], ENV['TWILIO_AUTH_TOKEN']
    @twilio_number = ENV['TWILIO_NUMBER']
  end
end

We can fetch all the stored recordings, but how can we record a new message? Let's see that next.

Record a new Message

If the organizer needs to make a new recording, we simply call her and record the call. Twilio makes this simple with the Record verb.

Here we Say something to the caller and then Record her message. There are many more options we can pass to Record, but here we simply tell it to stop recording when * is pressed.

class TwilioController < ApplicationController
  TWILIO_API_HOST = 'https://api.twilio.com'

  before_action :set_client_and_number, only: [:start_call_record, :broadcast_send, :fetch_recordings, :conference]

  # GET /conference
  def conference
    @conference_number = @twilio_number
  end

  # POST /conference
  def join_conference
    response = Twilio::TwiML::VoiceResponse.new
    response.say("You are about to join the Rapid Response conference")
    gather = Twilio::TwiML::Gather.new(action: 'conference/connect')
    gather.say("Press 1 to join as a listener.")
    gather.say("Press 2 to join as a speaker.")
    gather.say("Press 3 to join as the moderator.")
    response.append(gather)

    render xml: response.to_s
  end

  # POST /conference/connect
  def conference_connect
    case params['Digits']
    when "1" # listener
      @muted = "true"
    when "3" # moderator
      @moderator = "true"
    end

    response = Twilio::TwiML::VoiceResponse.new
    response.say("You have joined the conference.")
    dial = Twilio::TwiML::Dial.new
    dial.conference("RapidResponseRoom",
      wait_url: "http://twimlets.com/holdmusic?Bucket=com.twilio.music.ambient",
      muted: @muted || "false",
      start_conference_on_enter: @moderator || "false",
      endConference_on_exit: @moderator || "false")
    response.append(dial)

    render xml: response.to_s
  end

  # POST /broadcast/record
  def broadcast_record
    response = Twilio::TwiML::VoiceResponse.new
    response.say("Please record your message after the beep. Press star to end your recording.")
    response.record(finish_on_key: "*")

    render xml: response.to_s
  end

  # POST /broadcast/send
  def broadcast_send
    numbers = CSV.parse(params[:numbers])
    recording = params[:recording_url]
    url = request.base_url + '/broadcast/play?recording_url=' + recording

    numbers.each do |number|
      @client.calls.create(
        from: @twilio_number,
        to: number,
        url: url
      )
    end
  end

  # POST /broadcast/play
  def broadcast_play
    recording_url = params[:recording_url]
    response = Twilio::TwiML::VoiceResponse.new
    response.play(recording_url)

    render xml: response.to_s
  end

  # GET /broadcast
  def broadcast
  end

  # POST /call_recording
  def start_call_record
    phone_number = params[:phone_number]

    @client.calls.create(
      from: @twilio_number,
      to: phone_number,
      url: "#{request.base_url}/broadcast/record"
    )
  end

  # GET /fetch_recordings
  def fetch_recordings
    recordings = @client.recordings.list.map do |recording|
      {
        url:  full_recording_uri(recording.uri),
        date: recording.date_created
      }
    end

    render json: recordings
  end

  private

  # returns full uri given partial recording uri
  def full_recording_uri(uri)
    # remove json extension from uri
    clean_uri = uri.sub!('.json', '')

    "#{TWILIO_API_HOST}#{clean_uri}"
  end

  def set_client_and_number
    @client = Twilio::REST::Client.new ENV['TWILIO_ACCOUNT_SID'], ENV['TWILIO_AUTH_TOKEN']
    @twilio_number = ENV['TWILIO_NUMBER']
  end
end

We just saw how to list all recorded messages and how to record a new one. The last thing left is allowing a caller to broadcast one of those recorded messages. We'll see that next.

Broadcast a Recorded Message

This controller processes our voice broadcast webform, starting with the phone numbers our organizer provided. Because they are comma separated we can use Ruby's CSV class to parse them.

Next we initiate a phone call to each number using Twilio's REST API.

When Twilio connects this call it will make a request to the Url parameter to get further instructions. We include a recordingUrl parameter in that URL so that our Play action method will know which recording to use.

That makes the work for our Broadcast/Play route simple — we just Play the recording.

class TwilioController < ApplicationController
  TWILIO_API_HOST = 'https://api.twilio.com'

  before_action :set_client_and_number, only: [:start_call_record, :broadcast_send, :fetch_recordings, :conference]

  # GET /conference
  def conference
    @conference_number = @twilio_number
  end

  # POST /conference
  def join_conference
    response = Twilio::TwiML::VoiceResponse.new
    response.say("You are about to join the Rapid Response conference")
    gather = Twilio::TwiML::Gather.new(action: 'conference/connect')
    gather.say("Press 1 to join as a listener.")
    gather.say("Press 2 to join as a speaker.")
    gather.say("Press 3 to join as the moderator.")
    response.append(gather)

    render xml: response.to_s
  end

  # POST /conference/connect
  def conference_connect
    case params['Digits']
    when "1" # listener
      @muted = "true"
    when "3" # moderator
      @moderator = "true"
    end

    response = Twilio::TwiML::VoiceResponse.new
    response.say("You have joined the conference.")
    dial = Twilio::TwiML::Dial.new
    dial.conference("RapidResponseRoom",
      wait_url: "http://twimlets.com/holdmusic?Bucket=com.twilio.music.ambient",
      muted: @muted || "false",
      start_conference_on_enter: @moderator || "false",
      endConference_on_exit: @moderator || "false")
    response.append(dial)

    render xml: response.to_s
  end

  # POST /broadcast/record
  def broadcast_record
    response = Twilio::TwiML::VoiceResponse.new
    response.say("Please record your message after the beep. Press star to end your recording.")
    response.record(finish_on_key: "*")

    render xml: response.to_s
  end

  # POST /broadcast/send
  def broadcast_send
    numbers = CSV.parse(params[:numbers])
    recording = params[:recording_url]
    url = request.base_url + '/broadcast/play?recording_url=' + recording

    numbers.each do |number|
      @client.calls.create(
        from: @twilio_number,
        to: number,
        url: url
      )
    end
  end

  # POST /broadcast/play
  def broadcast_play
    recording_url = params[:recording_url]
    response = Twilio::TwiML::VoiceResponse.new
    response.play(recording_url)

    render xml: response.to_s
  end

  # GET /broadcast
  def broadcast
  end

  # POST /call_recording
  def start_call_record
    phone_number = params[:phone_number]

    @client.calls.create(
      from: @twilio_number,
      to: phone_number,
      url: "#{request.base_url}/broadcast/record"
    )
  end

  # GET /fetch_recordings
  def fetch_recordings
    recordings = @client.recordings.list.map do |recording|
      {
        url:  full_recording_uri(recording.uri),
        date: recording.date_created
      }
    end

    render json: recordings
  end

  private

  # returns full uri given partial recording uri
  def full_recording_uri(uri)
    # remove json extension from uri
    clean_uri = uri.sub!('.json', '')

    "#{TWILIO_API_HOST}#{clean_uri}"
  end

  def set_client_and_number
    @client = Twilio::REST::Client.new ENV['TWILIO_ACCOUNT_SID'], ENV['TWILIO_AUTH_TOKEN']
    @twilio_number = ENV['TWILIO_NUMBER']
  end
end

That's it! We've just implemented two major features of a Rapid Response Kit! Maybe in the future you can tackle some of the other features and build a full-fledge kit!

Where to next?

If you're a Ruby developer working with Twilio, you might enjoy these other tutorials:

Automated Survey

Instantly collect structured data from your users with a survey conducted over a voice call or SMS text messages. Learn how to create your own survey in Rails.

IVR Phone Trees

Create a fully functional automated phone tree, with some Reese's Pieces sprinkled about.

Did this help?

Thanks for checking out this tutorial! If you have any feedback to share with us, we'd love to hear it. Tweet @twilio to let us know what you think!