Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to record a voicemail if a number is not picked up in Twilio?

I am using Twilio in a PHP project, currently I am able to make calls and send SMS using its API as given below:

        $client = new \Services_Twilio($AccountSid, $AuthToken);
        try {
            // Initiate a new outbound call
            $call = $client->account->calls->create(
                "<From Number>",
                $input['phone'],
                array("url" => "http://demo.twilio.com/welcome/voice/")
            );
            //echo "Started call: " . $call->sid;
            \Session::flash("success","Calling to ". $input['phone'] ."");
        }

but now client wants to send voice messages if the call is not picked up.

like image 752
Amrinder Singh Avatar asked Dec 06 '22 14:12

Amrinder Singh


1 Answers

Twilio developer evangelist here.

Here's how it all works. When someone calls your Twilio number, Twilio will make an HTTP request, a webhook, to a URL you set in the number admin in your Twilio console for your phone number.

That URL needs to respond with some TwiML, which is just some XML markup to tell Twilio what to do with the call.

It sounds like, in your case, you want to dial your own number and after an amount of time take a message instead of continuing to ring. You will want two endpoints for this. The first one should do the dialling and the second is where we will redirect once the call is redirected for voicemail.

So, the first endpoint TwiML should look a bit like this, using <Dial> to forward the call:

<Response>
  <Dial timeout="30" action="/voicemail.php">
    <Number>YOUR_PHONE_NUMBER</Number>
  </Dial>
</Response>

We use the timeout attribute to set how long you want the phone to ring for. You can set that between 5 and 600 seconds. The action attribute is the endpoint we direct the call to once the timeout finishes. That endpoint will then read the caller a message to tell them to leave a message using <Say> for text to speech, then <Record> the message.

<Response>
  <Say voice="alice">Your call could not be answered at the moment. Please leave a message.</Say>
  <Record action="/hangup.php"/>
</Response>

I've added one extra action to the <Record> tag which just hangs up the call. That would look like this:

<Response>
  <Hangup/>
</Response>

There are other attributes you can use with <Record>. Most importantly, the recordingStatusCallback attribute takes a URL on which your application will be notified when there is a new recording.

For a bit more in depth reading about this, check out the guide on recording phone calls in PHP.

Let me know if this helps.

like image 185
philnash Avatar answered Dec 28 '22 08:12

philnash