How to Receive and Send voicemail from/on Twilio number? - twilio

I am creating a Twilio based application that will receive the Voicemail if the call is not picked up.
For now, I had set up the incoming call URL in the console against the phone number.
<?php
header('content-type: text/xml');
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
error_reporting(E_ALL);
ini_set('display_errors', 1);
file_put_contents('incoming_call.log', "\n" .json_encode($_REQUEST) . "\n", FILE_APPEND);
?>
<Response>
<Dial timeout="15" action="/voicemail.php">
</Dial>
</Response>
Whereas my voicemail.php file will has to code
<?php
// echo "hello ";exit;
header('content-type: text/xml');
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
file_put_contents('incoming_voicemail.log', "\n" .json_encode($_REQUEST) . "\n", FILE_APPEND);
?>
<Response>
<Say voice="alice">Your call could not be answered at the moment. Please leave a voice message.
</Say>
<Record></Record>
</Response>
I am not receiving the voicemail. Where can I setup the recordingStatusCallback attribute in twiml?
Secondly, I am trying to send voicemail from Twilio number to phone number by dialing One calling and again dial a Second call as the second call will receive a busy status and we are able to send a voicemail, but it's not working. My code is
$call = $twilio->account->calls->create(
$phone_no, // To
$from_no, // From
array(
"method" => "GET",
"statusCallback" => SURL . "voicemail?to_phone_no=" . $phone_no,
"statusCallbackEvent" => ["initiated","ringing"],
"statusCallbackMethod" => "POST",
"twiml" => '<Response><Say>Testing voicemail</Say></Response>'
)
);
sleep(3);
$call2 = $twilio->account->calls->create(
$phone_no, // To
$from_no, // From
array(
"url" => AURL.'Vm/audio_file'
)
);
Please guide me what I am doing wrong. For help thanks in advance.

Twilio developer evangelist here.
For your first question, if you don't include a number (or a SIP address, or a Client identity) to try to connect to, then the <Dial> will move straight on to the action URL, without bothering with the timeout.
If you want the <Dial> to try to connect to a phone, then you should add a phone number.
Second, if you want to receive a webhook when the recording is complete, then you need to add the recordingStatusCallback attribute, with a URL to send the webhook to, to your <Record>, e.g.:
<Response>
<Say voice="alice">Your call could not be answered at the moment. Please leave a voice message.
</Say>
<Record recordingStatusCallback="/recording-complete.php"></Record>
</Response>
Finally, we do not support the final use case of trying to dial a number twice in order to block it up and then leave a voicemail. Making calls and then dropping them is against the terms of service (see point 19 under "prohibited services". So I encourage you to consider a different way to reach out to your customers or contacts that engages with them in a legitimate way.

Related

Twilio API: Transferring connection to a forwarded number?

Im placing an outbound call, and based on the automated message from whom Twilio is calling, it calls my phone with the connection.
Here is the script that places the phone call.
import os
from twilio.rest import Client
account_sid = "xxxx"
auth_token = "xxxx"
client = Client(account_sid, auth_token)
call = client.calls.create( url='http://myhost.com/rec.php',to='+1234',from_='+9876')
print(call.sid)
The phone call is placed, and the action script sends a TwiML gather response. Here's rec.php
echo '<Response>
<Gather input="speech"
partialResultCallback="http://myhost.com/partial.php"
action="http://myhost.com/finalresult.php">
</Gather>
</Response>
I've got the partial page logging the text. But when I forward a call, my phone rings for one second, then disconnects. There's no errors in the debugger either.
Here's partial.php
if(contains("To continue in English", $_REQUEST['UnstableSpeechResult'])){
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<Response>
<Dial>+myPhoneNumber</Dial>
</Response>";
}
here is final result, which i think is called when the phone call is complete? im not sure.
if(contains("To continue in English", $_POST['SpeechResult'])){
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<Response>
<Dial>+myPhoneNumber</Dial>
</Response>";
}
According to the documentation, partialResultCallback doesn't process TwiML.
The webhooks Twilio makes to your partialResultCallback are
asynchronous. They do not accept any TwiML in response. If you want to
take more actions based on this partial result, you need to use the
REST API to modify the call.
Not sure how your phone is ringing given the above. Any more details you can provide will help troubleshoot the issue.

Call someone with Twilio then disconnect me and play a message to other person

I'm trying to create a button on a webpage (on my presonal PHP webserver) that should connect me (either call my cellphone or via the webclient), then call a number, I then want to have an options to either hangup the call, or just disconnect me but play an mp3 to the other person and then hangup.
I'm not sure how to go about it. I created a TwiML, but how do I connect that to the existing call? Or is there a different way to do it?
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Play>https://something-something.twil.io/assets/recording1.mp3</Play>
<Hangup/>
</Response>
Thanks in advance.
Twilio developer evangelist here.
This is an ideal use case for Answering Machine Detection. With Twilio's answer machine detection you can set it to Enabled or DetectMessageEnd which means that you can use Twilio to work out whether a machine has answered the call and wait until the message is over then play it a message. Otherwise you can connect the call to yourself.
With PHP, you can generate the call like this:
use Twilio\Rest\Client;
// Your Account Sid and Auth Token from twilio.com/console
$sid = "YOUR_ACCOUNT_SID";
$token = "YOUR_AUTH_TOKEN";
$client = new Client($sid, $token);
$call = $client->calls->create(
"+14155551212", "+14158675309",
array(
"url" => "http://example.com/calls",
"MachineDetection" => "DetectMessageEnd"
)
);
Then, for your URL, you need to respond to the call depending on what the machine detected. You do that with the AnsweredBy parameter. Something like this, which dials your number if someone answers or speaks a message using <Say> if a machine answers:
<?php
if ($_REQUEST['AnsweredBy'] == "human") {
echo "<Response><Dial><Number>YOUR_NUMBER</Number></Dial></Response>";
} else {
echo "<Response><Say>Hello, this is my message</Say></Response>";
}
Let me know if that helps at all.
Edit
Without Answering Machine Detection
Ok, to do this without Answering Machine Detection I recommend you build yourself a dialler using Twilio Client JS. There is a quickstart guide here, so I won't go through how that works here.
Once you have a dialler you can use it to initiate the phone calls. The issue is then moving the voicemail calls to play the message. I would build two buttons, one that hangs up as if you've completed the call successfully and the other that plays the message instead. The first button is a simple function call to Twilio.Device.activeConnection().disconnect().
The second one needs a couple of things. The idea is that it will make a call to your server to redirect the other call to a new set of TwiML.
First up, you need the SID of the call you created. You can get that from the connection object you receive in response to calling connect.
var connection = Twilio.Device.connect({ number: "+1234567890" });
var callSid = connection.parameters.CallSid;
When you want to hangup and play a message you need to send this to your server. This is the SID of the parent call though, and you need to get the child call, the other leg. So, on your server you need to use the REST API to get the other call, then redirect it.
use Twilio\Rest\Client;
// Your Account Sid and Auth Token from twilio.com/console
$sid = "YOUR_ACCOUNT_SID";
$token = "YOUR_AUTH_TOKEN";
$client = new Client($sid, $token);
$calls = $client->calls->read(
array("ParentCallSid" => $_REQUEST['CallSid'])
);
// Loop over the list of calls, it should only have one call in it, and redirect the call to a URL that has the message TwiML
foreach ($calls as $call) {
$call->update(array(
"url" => "http://example.com/message.xml"
));
}
When you redirect the child call, the parent call will no longer be connected so it will hang up. The URL you redirect the child call to should contain the TwiML required to play the message to the machine using <Say> or <Play>.
I think I get what you're trying to do. You have a list of people you're trying to call. The app will call them and connect you. If you hear an answering machine, you want to press a key then hangup and move on to the next call. But after you hang up, that first outbound call stays online and leaves a .mp3 message to that recipient?
I believe one solution would be creating a conference with a bot.
Your app makes an outbound call to you, to the bot and to the recipient and puts everyone into a conference room called "room-timestamp" where timestamp is the current time. The bot is a twilio number that listens for a Gather dtmf. If you press 1, it will play message 1 then hang up. But because this is a conference, you can hangup at anytime and move on to the next call.
The bot could loop a few times and if no dtmf is detected, it will hang itself up.
This is all made easier using the new Outbound conference API where you can pass it the conference name instead of conference SID :
https://www.twilio.com/docs/api/rest/participant#list-post
Edit:
Connect three numbers to a conference room :
$uniqueid = time();
$call = $client->account->calls->create($officeline,$twilionum,
array("url" => "http://yourdomain/conference.php?id=$uniqueid"));
$call = $client->account->calls->create($botline,$twilionum,
array("url" => "http://yourdomain/conference.php?id=$uniqueid"));
$call = $client->account->calls->create($customerline,$twilionum,
array("url" => "http://yourdomain/conference.php?id=$uniqueid"));
This will connect three numbers to a conference room:
$officeline (your number),
$botline (twilio phone # of a bot that responds to dtmf)
$customerline (the customer you're calling)
conference.php just returns a conferenceID for calls to connect to:
header('Content-Type: text/xml');
$confid = $_REQUEST['id'];
echo<<<XMLOUT
<?xml version="1.0" encoding="ISO-8859-1"?>
<Response>
<Dial>
<Conference statusCallbackEvent="leave" statusCallback="killconference.php">$confid</Conference>
</Dial>
</Response>
XMLOUT;
killconference.php is called so that the conference can be terminated when there's only one person left. Just make sure your bot hangs up after playing something.
killconference.php
$theconference = $_REQUEST['ConferenceSid'];
$participants = $client
->conferences($theconference)
->participants
->read();
if (count($participants) == 1) {
$conference = $client
->conferences($theconference)
->fetch();
$conference->update(array(
"Status" => "completed"
));
}
your botline twilio number will be pointing to bot.php that responds to dtmf:
bot.php
header('Content-Type: text/xml');
$dtmf = isset($_REQUEST["Digits"]) ? $_REQUEST["Digits"] : "";
$playmore = "";
if ($dtmf == "1") {
$playmore = "<Say>Hey I just wanted to leave you a message </Say><Hangup/>\n";
}
if ($dtmf == "2") {
$playmore = "<Play>http://www.soundboard.com/mediafiles/22/224470-33a9f640-d998-45a3-b0c1-31c1687c2ae4.mp3</Play><Hangup/>\n";
}
echo<<<XMLOUT
<?xml version="1.0" encoding="ISO-8859-1"?>
<Response>
$playmore
<Gather action="bot.php" numDigits="1" timeout="30">
</Gather>
<Hangup/>
</Response>
XMLOUT;
The bot will stay on the line for 30 seconds, if no dtmf is entered it hangs itself up. Press 1 to leave the customer a message, 2 for Leroy Jenkins

Play music while waiting an answer in TWIML <dial>

How to dial numbers and diffuse a music to the caller while waiting a successful connexion ?
The code below waits the music to end before doing the <dial> (which is logic)
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Play>http://com.twilio.music.ambient.s3.amazonaws.com/gurdonark_-_Plains.mp3</Play>
<Dial timeout="10" callerId="+1234567890">
<Number url="whisper?id=1">+1122334455</Number>
<Number url="whisper?id=2">+1122334466</Number>
<Number url="whisper?id=3">+1122334477</Number>
</Dial>
</Response>
NB: It would be nice NOT to use conference functionalities. Something with <Enqueue> maybe ?
Twilio developer evangelist here.
You could do this with <Enqueue>. Here's how it would work:
You would need replace the TwiML that <Play>s and then <Dial>s. This would have to be a dynamic action as you would need to make the three simultaneous calls using the REST API instead of TwiML. The TwiML that you would return would put your original caller into a queue as you suggest and play them music. In PHP that would look a bit like:
<?php
// Get the PHP helper library from twilio.com/docs/php/install
require_once '/path/to/vendor/autoload.php';
use Twilio\Rest\Client;
// Your Account Sid and Auth Token from twilio.com/user/account
$sid = "your_account_sid";
$token = "your_auth_token";
$client = new Client($sid, $token);
$numbers = array('+1122334455', '+1122334466', '+1122334477');
foreach ($numbers as $number) {
$call = $client->calls->create(
$number, $YOUR_CALLER_ID,
array("url" => "http://example.com/dial_queue")
);
}
header("content-type: text/xml");
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
?>
<Response>
<Enqueue waitUrl="http://com.twilio.music.ambient.s3.amazonaws.com/">
dialling
</Enqueue>
</Response>
At the URL http://example.com/dial_queue you would need to return TwiML that dials the callee into the original caller. You have a whisper URL in your original example, which you can achieve by inlining that into the TwiML.
<Response>
<Say>Your custom message</Say>
<Dial>
<Queue>dialling</Queue>
</Dial>
</Response>
Note that you dial the name of the <Queue> that you used in the original <Enqueue>. If this system will be used for more than one caller, then you probably need to generate unique queue names for them.
The final things to do would then be to cancel the other two calls once a call connects and cancel the queue if none of the calls answer. I will leave that to you as I'm sure there's many ways you could achieve it with your own setup.
Let me know if that helps at all.

Is there a way we can dial two numbers and make them join a conference

I am new to Twilio. Is it possible to make calls to two phone numbers and join them into a conference using Twilio-PHP? I know we can join two received calls into a conference, I'm wondering if we can do the same with two dialed calls. If yes , I would be grateful if someone refers me to that part of documentation.
Thanks in Advance.
Twilio developer evangelist here.
You absolutely can do that. When you initiate a call from within Twilio you pass three arguments, the number you're calling from, the number you're calling and a URL. That URL should point to some TwiML and you can use it much in the same way you would when you receive a call. When the outbound call is answered that's when Twilio looks at the URL to find out what to do with the call.
So, here's an example, assuming you've required the Twilio PHP library and set up the relevant variables:
// Make an API client
$client = new Services_Twilio($sid, $token, $version);
// Use the API client to create an outbound call
$call = $client->account->calls->create(
$to,
$from,
'http://example.com/conference.php'
);
Then, at your URL, in this case example.com/conference, you just need to return some TwiML to enter the people being called into the conference. So, you'd need a conference.php file that looked a bit like this:
<?php
header("content-type: text/xml");
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
?>
<Response>
<Dial>
<Conference>YOUR_CONFERENCE_ID</Conference>
</Dial>
</Response>
Let me know if that helps at all.

Twilio initiate outbound call that connects agent phone before dialing target number

I want to create a help desk web page in which an agent can click a link to initiate an outbound call to a target number. I understand how to use the Web Client to make that happen, but for an agent who doesn't have bandwidth to support VoIP, I'd like Twilio to call the agent's phone number then dial the target number.
The experience would be much like using Google Voice with Google Chat/Hangout client -- Google Voice calls your number/client, then initiates a call to the target.
Also, if both agent and target phone numbers are domestic landlines, would this scenario incur 2X the per minute landline fees?
I'm not looking for code necessarily, but rather an answer based on Twilio APIs and Twiml concepts.
Twilio evangelist here.
Sounds like you are looking to create "Click to Call". Here is some code from our docs that shows how to do this:
https://www.twilio.com/docs/howto/click-to-call
The basics are:
Use the REST API to initiate an outbound call. When that call is answered Twilio is going to make an HTTP request to some URL that you told about in your initial REST request. That URL's job is to return TwiML that contains the <Dial> verb which tells Twilio to dial the second phone number and bridge the two call legs together.
For domestic US calls, the total cost is going to be 4 cents / minute. 2 cents per each leg, since each leg is considered outbound. See Example 4 on this page:
https://www.twilio.com/help/faq/voice/how-much-am-i-charged-for-call-forwarding
Hope that helps.
Simple/Direct Twilio Calls Agent->Call
original url: https://www.twilio.com/docs/quickstart/php/rest/call-request#call-end-callback
First file loaded from browser:
use Twilio\Rest\Client;
// Step 2: Set our AccountSid and AuthToken from https://twilio.com/console
$AccountSid = "SID";
$AuthToken = "AuthTok";
// Step 3: Instantiate a new Twilio Rest Client
$client = new Client($AccountSid, $AuthToken);
try {
// Initiate a new outbound call
$call = $client->account->calls->create(
"+12125551111",// connect this number(Agent)
// that you've purchased or verified with Twilio.
"+12135554646",// caller id for call
// Set the URL Twilio will request when the call is answered.
array("url" => "http://example.com/call_them.php")
);
echo "Started call: " . $call->sid;
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
call_them.php:
<?php
header("content-type: text/xml");
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
//inside dial.. actual number you want to reach
?>
<Response>
<Dial>+18185556363</Dial>
</Response>
Thank you for the great answer, #user3229526, it worked like a charm.
In order to unhardcode the number to call, just append the number you wish to call as a URL parameter in the Twilio Requst URL
array("url" => "http://example.com/call_them.php?number=1234567890")
And edit call_them.php to accept that parameter
<Response>
<Dial>
<?php echo '+1'. $_GET['number']; ?> // +1 for country code
</Dial>
</Response>

Resources