How to receive a browser call using twilio to a phone number using javascript - twilio

Ok guys, I've been viewing twilio tutorials for the last couple hours and I seem to just not get it. Can someone give me a basic rundown on how to do the following?
I want to create an app that uses the microphone/speaker of my computer to receive a call.
I have a twilio account with a twilio voice phone # but I just don't seem to get how to connect a JS Device object to a phone #. I think it has something to do with a capability/auth token but can someone give me a step by step on how a phone # can be called and the headset will receive a voice call and begin the conversation. The tutorials show how you can make twilio speak a written statement in twiML but I don't understand how to make it make an actual voice call.
My current guess is that I need to do the following in the browser to accept a call. But I'm not sure what needs to be inside the token.
//I don't know what needs to be in the token in order to connect this
//web page twilio 'Device' to. I use c# but if you have a node.js or php example that would be fine
fetch('https://mybackend/getPhoneToken').then((token) => {
const device = new Device(token);
device.on('incoming', call => {
call.accept();
});
});
Thank you for your help.

This is my first answer, let's see if I can help.
First you have to generate the access token by giving the Voice grant.
Generate access token with your account sid, API key ,API key secret and identity.
access_token = AccessToken(<Account_sid>, <api_key>,<api_secret>, identity=identity)
Note: Identity Should be unique for each user. You can put identity as twiliophonenumber_userid
Grant the Voice incoming Access.
voice_grant = VoiceGrant(outgoing_application_sid=<twiml_sid>,incoming_allow=True)
Add grant to the access_token
access_token.add_grant(voice_grant)
Initialise the Twilio device with this access_token. Then you can make the incoming call to the twilio number and receive the call on browser.
You just need only one Twiml App for all the twilio phone numbes. Create a Twiml App with Request Url and method. (Whenever the js device make/receive calls, then twilio will send a request to this URL to get further instructions)
In the above Request URL function, you have to tell twilio what needs to do with the request. Here is a sample function
function handle_calls():
if outgoing_call:
dial.number(customer_phone_number)
else:
# handle incoming call
dial.client(identity) # This is the same identity which we have given while generating access_token. This will trigger "incoming" event on Js device.
To differentiate between outgoing / incoming calls, you can send extra parameters to twilio while making outgoing calls and handle the request accordingly in the above function (pt. 6). See below sample function.
var params = {"direction":"Outgoing"} # Based on this parameter you can differentiate between outgoing/incoming calls.
device.connect(params)
You can setup status_callback events to better handle the call progress. have a look at this article...https://www.twilio.com/docs/voice/twiml/number#attributes-status-callback-event
Have a look at this article, you can get some more information - https://www.twilio.com/blog/generate-access-token-twilio-chat-video-voice-using-twilio-functions

Related

How make a direct phone call to exist between two customers using Twilio API

I have this idea where I need to connect customer A (who is hiring) with customer B (who is to be hired) via a direct phone call with just a push of a button, and customer B (who is to be hired) don't want anyone to just have access to his personal phone number (to avoid spam calls).
Well, to make this work I found out that Twilio can handle programmable voice calls which I implemented using ASP.NET Core but that's not exactly what i wanted because customer A (who is hiring) is not allowed to speak directly with customer B (who is to be hired) while the TwiML is at work.
Using Twilio, is there a way for these two customers to communicate via direct calls while hiding the phone number of customer B (who is to be hired) from customer A (who is hiring)? To throw more light to this, on behalf of customer A I want to place a call to customer B's phone number using Twilio's phone number. Any help will be appreciated, thank you.
Twilio developer evangelist here.
You absolutely can connect two customers via a direct call while hiding customer B's number.
I'll give you the very basics first, then suggest some ways to make it more scalable.
To create a number that A can call that will connect A to B you need to buy that number from Twilio and configure it so that when a call comes in to A it returns TwiML that connects to B. For this initial example, you could use a TwiML Bin or some static TwiML that you host. The TwiML needs to use <Dial> and <Number>, like this:
<Response>
<Dial callerID="YOUR_TWILIO_NUMBER">
<Number>Customer B's phone number</Number>
</Dial>
</Response>
Now, when A calls the number they will get connected to B. And if you set the callerId to your Twilio number it will also appear to B to come from your Twilio number, keeping their phone number private too.
Using hard-coded TwiML like this doesn't scale though. You have a few options to improve this.
First, you could have A initiate the call from your application, by clicking a button. That button could trigger a call to A using the REST API and pass it the TwiML above so that when A answers the phone
it then dials B. Like:
using System;
using Twilio;
using Twilio.Rest.Api.V2010.Account;
class Program
{
static void Main(string[] args)
{
// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
string accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");
string authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");
string twilioNumber = Environment.GetEnvironmentVariable("TWILIO_NUMBER");
TwilioClient.Init(accountSid, authToken);
var call = CallResource.Create(
twiml: new Twilio.Types.Twiml($"<Response><Dial callerId='{twilioNumber}'><Number>CUSTOMER_B_NUMBER</Number></Dial></Response>"),
to: new Twilio.Types.PhoneNumber(CUSTOMER_A_NUMBER),
from: new Twilio.Types.PhoneNumber(twilioNumber)
);
Console.WriteLine(call.Sid);
}
}
Another alternative is to let A call directly from within your application using Twilio Client to make the phone calls from your browser.
To dig a bit deeper, you can also use Twilio Proxy to create a session between the two customers and your Twilio number, creating a connection that would allow either of A or B to call the Twilio number and get connected to the other for the duration of the session. Under the hood Proxy works to automate the delivery of the TwiML described above whilst also maintaining the session between the users until it is done with and the number can be reused by customer A to connect to a new customer. Check out the Proxy quickstart to get a better idea how it works.
Using one of Twilio Proxy or Twilio Client is probably the best for your application, but it depends on the interface you want to provide for your users.

How do I call a number with Twilio Studio flow REST API execution

The purpose is simply to call a number (my number) and have a message start playing.
I have created a Studio Flow like so:
And published that flow.
I've also bought a phone number and it is activated for voice & messaging. I can receive a test voice call with code and using TwiML).
In the settings of my phone number I have the following:
Accept: Voice Calls
Configure with: .. Studio ..
A call comes in: Studio Flow (and selected the correct flow)
I then proceed to use Postman to try and trigger my Flow using a POST request with the following parameters:
And the following body parameters where the To number is my number which is verified in my trial account, and the from is the number i purchased in twilio:
After clicking on Send in postman I receive a 200 OK message, but I am not receiving a call on my phone. What step am I missing?
Twilio developer evangelist here.
The variable you are using as the number to dial out from Studio is {{contact.channel.address}} but the contact variable refers to "data about the current contact engaging with your flow, such as their phone number".
Since you have triggered the flow with a REST API call there is not a contact that is currently engaging with the flow, so this won't give you the number you want.
You are, however, sending in some parameters from your HTTP request from Postman, notably a To parameter. Your data that you send to the flow endpoint like this will be available under the trigger context variable.
So, you should update your widget to use {{trigger.To}} instead (and you probably don't need From, as that is the number associated with the flow, or Body).
Let me know how you get on with that.

App - App Call in Twilio

I had been trying to sort out how can I make an app to app call using Twilio SDK, every time I end up reading the documentation that make me call a Phone number.
Can anyone please guide me towards the right direction ?
I have been following this link for long:
https://www.twilio.com/docs/quickstart/client/ios#gather-twlio-account-information
Twilio developer evangelist here.
With the quick start tutorial that you have been following, there is an example application that can make calls to both phone numbers and to other applications. The key is, instead of setting a phone number when you dial, you can also set another client identity. The quick start server applications for this give the example app a random identity which you can see in the top bar of the app, which you can use in this case.
So, when you type in another client identity, device.connect is called with a dictionary with one key, To, set to the identity (https://github.com/TwilioDevEd/client-quickstart-swift/blob/master/SwiftTwilioClientQuickstart/DialViewController.swift#L165):
connection = device.connect(["To":dialTextField.text!], delegate: self)
This will then be present in the request that Twilio makes to your TwiML app and, taking the Ruby example server as our example here, you can then use this identity to return a TwiML <Dial> to another <Client> (rather than a <Number>).
The key overall is that you set an identity for each of your application users (which is random in the example), you can then call other identities by passing the identity you want to call into device.connect and reading that out of the parameters in Twilio's request to your TwiML application. If you then return TwiML to direct Twilio to <Dial> the <Client> with the identity you sent then an app to app call will be made.
Let me know if that helps at all.

Twilio Browser client Available or not

I am facing a problem with Twilio to detect the Twilio Browser client Available or not.
If Twilio client is not available then need to send the voicemail otherwise I am using to accept the call.
Twilio.Device.incoming(function (conn);
Thanks.
Sounds like you need agent presence. There are a couple ways to go about this. One (Recommended) is to use Twilio TaskRouter. https://www.twilio.com/taskrouter. This will handle agent presence for you (online, offline, busy, etc..) and much more
Your other option is to use a service like PubNub http://www.pubnub.com/ and bind the clint so you can get state information (online, offline, busy, etc..). This is more wok since you have to handle state yourself.
The following steps can be followed to achieve this
 1. Set a valid url to the action attribute of the Dial verb of the client
  Eg., The TwiMl to dial the client must be
  <Response>
   <Dial action="myapp/statusCallBack">
    <Client>jenny</Client>
   </Dial>
  </Response>
 2. If the client jenny is available, the connection object can be received via
  Twilio.Device.incoming(function (conn){conn.accept();});
 3. If the client jenny is unavailable, Twilio will request to the statusCallBack url with the parameter 'DialCallStatus=no-answer'. Now the following
  twiml can be returned to say Unavailable message.
  <Response>
   <Say>
    Please leave your name and number along with a short message.
   </Say>
   <Record maxLength="3600" action="myapp/recordedUrl">
   </Record>
  </Response>
 4. Now the voicemail url can be stored when the "myapp/recordedUrl" is called once the caller recorded the voicemail. For more info on record verb, visit this site
 Note that the voice mail is recorded on two cases, if the client is unavailable or the client does not accept the call.

How to set the From identifier for Twilio Client (VoIP) outgoing calls?

Our application accepts phone calls or VoIP connections via the twilio.js client into our twilio endpoint. Phone calls are logged by caller ID, but VoIP connections all appear as Anonymous in the twilio call log, e.g.:
Date Direction From To Type Status Recording Duration
XXYY Incoming Anonymous --- Client Completed --- 17 min 7 sec
YYZZ Incoming Anonymous --- Client Completed --- 17 min 23 sec
Is there a way to set the From field for outgoing (client->twilio) calls? Looked through Twilio.Device.connect as well as the capability token docs and couldn't find any hints.
It all ties into the capability token step, in a completely undocumented (and apparently unknown to Twilio themselves) manner.
In order to get the twilio logs to identify the VoIP endpoint that called into a conference, we had to bind the client ID to the allow_client_incoming capability, and make sure the ID was a straight alphanumeric (e.g. dashes in the string prevented the ID from coming through).
In our server side (ruby) token generation step, it looks something like this:
capability.allow_client_incoming sanitized_client_id
Twilio evangelist here.
When Client connects to your TwiML app endpoint, the From parameter that is passed to the Voice Request URL should be the name of the client.
If that Voice Request URL includes the <Dial> verb telling Twilio to make an outbound phone call and bridge it with the Client call, you can set the callerId parameter:
<Dial callerId="+15555555555" />
Hope that helps.
What worked for me was to set the clientName parameter in the OutgoingClientScope capability.
This is a code sample in js:
capability.addScope(
new ClientCapability.OutgoingClientScope({
clientName: 'mike',
applicationSid: 'AP...'
})
);
None of the other answers worked for me.

Resources