Twilio API for making outbound calls with a speech stream - twilio

I have a scenario where say at 5.00 AM every morning, I have a server side script / batch job that wakes up, selects a phone number from a list based on an algorithm, places a call to that phone number and uses text-to-speech to deliver a customized message. I have 2 questions,
Which Twilio API can I use to achieve this? Bear in mind there is no app UI and all the code would be on the back end. Think NodeRED flow or a Python script that is made to run at a given time.
Instead of specifying the text in the TwiML, can I pass say an audio stream from Watson's Text to Speech to the appropriate Twilio API?

To do this, you would need to use the programmable voice API from Twilio. This lets you play audio files, text to speech, make and manipulate phone calls, etc. I have never used Watson Text-to-Speech, but, if it can output an audio file you can play that with Twilio TwiML.
Here's an example in Node.
npm install twilio
//require the Twilio module and create a REST client
var client = require('twilio')('ACCOUNT_SID', 'AUTH_TOKEN');
client.makeCall({
to:'+16515556677', // Any number Twilio can call
from: '+14506667788', // A number you bought from Twilio
url: 'url/to/twiml/which/may/have/WatsonURL' // A URL that produces TwiML
}, function(err, responseData) {
//executed when the call has been initiated.
console.log(responseData.from); // outputs "+14506667788"
});
The TwiML could look like this:
<Response>
<Play loop="1">https://api.twilio.com/cowbell.mp3</Play>
</Response>
This would play the cowbell sound from the Twilio API. Just a default sound. This could be easily generated to play a Watson sound file if you can get a URL for that.
You could do the same thing in Node, if you'd rather not build the XML manually.
var resp = new twilio.TwimlResponse();
resp.say('Welcome to Twilio!')
.pause({ length:3 })
.say('Please let us know if we can help during your development.', {
voice:'woman',
language:'en-us'
})
.play('http://www.example.com/some_sound.mp3');
If you were to take this toString() it would output formatted XML (TwiML):
console.log(resp.toString());
This outputs:
<Response>
<Say>Welcome to Twilio!</Say>
<Pause length="3"></Pause>
<Say voice="woman" language="en-us">Please let us know if we can help during your development.</Say>
<Play>http://www.example.com/some_sound.mp3</Play>
</Response>
Hopefully this clears it up for you.
Scott

Related

Gathering speech during outbound twilio voice call

I am trying to create a voice call from twilio to a number using programmable voice.
I also intend to gather recipient's speech transcribed. However, the documentation contains examples and tutorials only for inbound voice calls.
This is what I have tried-
Initiating voice call:
client.calls
.create({
twiml: `<Response><Gather input="speech" action="https://ngrok-url-for-my-local-server/voice" method="POST" speechTimeout="5"><Say>Hey there, How are you?</Say><Pause length="4" /></Gather></Response>`,
to: toPhoneNumber,
from: myPhoneNumber,
})
.then((call) => {
console.log(call.sid)
console.log(call)
})
.catch((e) => {
console.log(e)
})
Code in handler for gathering speech-
const VoiceResponse = twiml.VoiceResponse
const res = new VoiceResponse()
res.gather()
console.log(res.toString())
However I am not getting anything useful in the console.
Can anybody point me to a useful tutorial or example or tell me what I should do ?
You need to first make the call and then modify the call to gather.
When you make the call using the new VoiceResponse() call you will be returned a SID for the call. Next, use that SID to modify a call that is in progress by redirecting to the Twiml to gather the digits.
You will have three legs:
Make the outbound call (you provided this code in your questions).
Modify the active outbound call by using the call's SID to redirect to a Gather twiml.
After the gather has finished tell the call what do to using the action parameter of the gather. Here is an example.
If you are trying to go for a conference bridge type feature where you press * to move into an admin type menu, you will need a more complex solution involving a conference call.

Twilio JS send digits in VoIP call

I want to implement one functionality in VoIP call using twilio. Like if someone is calling to the customer care numbers and in that case they have to dial some numbers to navigate like dial some number choose language and dial some number to talk to representative.
So, to implement this in my application with VoIP call, I have tried this so far.
Here is my generated TwiML response at the time of VoIP start
<Response>
<Dial timeLimit="7200" callerId="+19782880482" record="record-from-answer-dual">
<Number statusCallbackEvent="initiated ringing answered completed" statusCallback="http://0affe80b.ngrok.io/call/twilio/events" statusCallbackMethod="POST"></Number>
</Dial>
<Record timeout="10" maxLength="7200"/>
</Response>
And in frontend part, on each digit press I am sending a digit to current active connection like this,
function onNumberPress(number){
var connection = Twilio.Device.activeConnection();
connection.sendDigits(number);
}
But, now at the time of sendDigits function, I am getting this error
TypeError: a.match is not a function
at a.sendDigits (twilio-1.3.21.min.js:19)
Note: I am able to get active connection here.
After surfing I found that I need to supply Gather keyword in TwiML. But do I need to pass those in this case? I think its not needed in My described case.
Am I on right track? Is this possible to achieve? If then what am I missing here?
Twilio developer evangelist here.
The connection.sendDigits function takes a string as an argument (as it can be any digit as well as # or *). I think you may be passing a number to it instead. Try ensuring that the digits you send are strings.

Retrieve Key Input before recording a users call when making calls within Twilio

We have currently developed a phone system for our call centre using Twilio (mainly c#, angular2 and typescript). Our company is currently in the UK but we have now started expanding out to the USA and because of laws in the US it looks like we'd need the ability to choose when we turn on the call recording. In the US people have to consent to recording the call before you can start recording them. I am trying to - when we make an outbound call via twilio to first play a message and get the user to input a key on their dialer to consent to recording the call before continuing with the call. I have attempted to use the gather and say verbs after we have dialled out but this doesn't seem to work. Code below:
`
public override void ApplyAction(TwilioResponse response)
{
var attributes = this.GetAttributes<DialAttributes>("attribute-");
attributes.callerId = this.PhoneNumber;
response.Dial(new Number(this.ReceiverPhoneNumber), attributes);
response.Gather(
new
{
timeout = 10,
finishOnKey = '*'
});
response.Say("We record all calls - please press the star key to consent to call recording");
}`
Twilio developer evangelist here.
The problem is that you are performing the <Dial> before the <Gather>
and <Say>. If you want the user to approve the call first you need to nest the <Say> in the <Gather> and provide an action URL for the <Gather>. When the user presses a button as part of the <Gather> Twilio will make an HTTP request to the action URL with the results in the Digits parameter. Then you should return the <Dial> as the response to that request, if the user signifies agreement. This way you ask them first and then connect the call.
Let me know if that helps.

Call method for Twilio on Parse Cloud Code

We are trying to implement simple P2P VoIP connection between iOS devices. We picked Twilio to handle calls and using Parse to interact with Twilio.
We are successfully generating capability tokens per user and initiate a call. However call is hanging up instantly after successful connection.
Receiver is receiving the call successfully and hearing the trial message.
Initiator is hearing the trial message and also "Application error occurred.".
We are suspecting that there may be something wrong at our call method on Parse Cloud Code.
app.get('/call', function(request, response) {
var client = require('twilio')('ACC_ID', 'AUTH_ID');
// Create a TwiML response generator object
var fromName = 'client:' + request.query.from;
var toName = 'client:' + request.query.to;
client.makeCall({
to:toName, // Any number Twilio can call
from: fromName,
url: 'http://xxxyyzz.parseapp.com/consult' // A URL that produces an XML document (TwiML) which contains instructions for the call
}, function(err, responseData) {
//executed when the call has been initiated.
console.log(responseData.from); // outputs "+14506667788"
});
});
We are not sure about what should url parameter supposed to do.
app.post('/consult', function(request, response) {
response.send();
});
Thanks.
You are almost there, but there seems to be a problem in your /call service (you also don't need any other urls, /call' should be enough).
What Twilio expects as a response from /call is a TwiML message (https://www.twilio.com/docs/api/twiml). Your server here should respond proper TwiML so that Twilio will know what to do.
If you want to connect two clients then /call should return the Dial TwiML message. The documentation (https://www.twilio.com/docs/api/twiml/dial) can let you know about the details of the Dial message. There are some interesting options such as limiting the phone call to 40 seconds for example.
If you want to dial a client called 'Jenna', then the response from your /call service should be:
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Dial>
<Client>Jenna</Number>
</Dial>
</Response>
Good luck with your application, hope this helps!

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