Using Twilio API I managed to make a call and play one audio file, but I did not succeed to play two files. how can I do it?
Here is my code:
public HttpResponseMessage Call(string callToNumber, string audioUrl)
{
// Set our Account SID and AuthToken
var accountSid = ConfigurationManager.AppSettings["ACCOUNT_SID"];
var authToken = ConfigurationManager.AppSettings["AUTH_TOKEN"];
var twilioNumber = ConfigurationManager.AppSettings["TwilioMobileNumber"];
// Instantiate a new Twilio Rest Client
var client = new TwilioRestClient(accountSid, authToken);
// Initiate a new outbound call
var call = client.InitiateOutboundCall
(
twilioNumber,
callToNumber,
audioUrl
// ,audioUrl2 -- I want to add another file
);
return Request.CreateResponse(HttpStatusCode.OK);
}
Twilio evangelist here.
Is the audiofile variable just a URL to a wav or mp3? If it is, then you'll need to change that to a URL that can return some TwiML that includes two <Play> verbs, like this:
<Response>
<Play>http://example.com/music1.mp3</Play>
<Play>http://example.com/music2.mp3</Play>
</Response>
Hope that helps.
Related
I am new in Twilio and trying to develop an IVR that at some point runs a function (Run Fuuntion Widget). The function should send http request including the user phone number to a service provider to make payment for a product selected by the user.
I tryed the code bellow but the variable is not getting the user phone number.
exports.handler = function(context, event, callback) {
let twiml = new Twilio.twiml.VoiceResponse();
var Client = require("#paymentsds/mpesa").Client;
var phoneNumber = event.From
var phoneNumberNorm = phoneNumber.substring(4);
var client = new Client({
apiKey: 'xxxxxxxxxxxxxxxxxx', // API Key
publicKey: 'xxxxxxxxxxxxxxxxxx', // Public Key
serviceProviderCode: '171717' // input_ServiceProviderCode
});
var paymentData = {};
paymentData['from'] = phoneNumberNorm;
paymentData['reference'] = '11114';
paymentData['transaction'] = 'T12344CC';
paymentData['amount'] = '10';
client.receive(paymentData).then(function(r) {
// Handle success scenario
twiml.say("Your payment was successfull");
callback(null, twiml);
}).catch(function(e) {
// Handle success scenario
twiml.say("Your payment failed");
callback(null, twiml);
});
};
Twilio developer evangelist here.
You will need to pass the phone number into the Function via the Run Function widget.
You need to add a Function Parameter, for example From, and then the data you want to pass, which for the incoming phone number is {{contact.channel.address}}. Like so:
Then you can use event.From in your Function code.
Am trying to setup a soft phone in browser, via TWiML app.
I created the following:
A page on my own server which serves TWiML to dial a number, say '+11111111111'.
A TWiML app which points to that page
A Twilio number which points to that app.
A page on my server which creates a Twilio Device associated with the app and buttons to run device.connect() or device.register()
The device is setup correctly, as I can register and connect with no errors.
The app works - the phone rings at +111 when I press "Call Using Twilio" button on the TWiML app page, when I call the number pointing to the TWiML app, and when I press the button on my own page. Yay!
What I cannot figure out:
How to answer the phone using the Twilio Device.
The device registers with no issue, so why doesn't it get incoming calls?
How to call other numbers aside from the one in my app.
I did in device.connect({params: {To: '+2222222222'}}), why doesn't it call that number?
Here are all the relevant pages:
calls.pug:
doctype html
html(lang="en")
head
meta(charset="utf-8")
title Browser Calls
body
input#call(type="submit" value="call")
input#register(type="submit" value="register")
pre
script(src="/js/twilio-sdk/twilio.js")
script(type="module" src="/js/calls.js")
[client] calls.js
const $ = css => document.querySelector(css);
const echo = msg => $('pre').innerText += msg + "\n";
var device;
async function setupDevice(){
let data = await fetch('/token/new');
data = await data.json();
device = new Twilio.Device(data.token);
device.on("error",
err => echo("Twilio.Device Error: " + err.message));
echo ('Device setup complete.')
}
$('#register').addEventListener('click', async e => {
if (!device) await setupDevice();
device.on("registered", conn =>
echo('Ready to accept incoming calls.')
);
device.on("incoming", call =>
echo('Incoming call to device')
);
device.register()
});
$('#call').addEventListener('click', async e => {
if (!device) await setupDevice();
let params = { To: '+22222222222' }
device.connect({ params })
});
[node] token.js
const express = require('express');
const router = express.Router();
const AccessToken = require('twilio').jwt.AccessToken;
const VoiceGrant = AccessToken.VoiceGrant;
const config = require('../config');
router.get('/new', function (req, res) {
const accessToken = new AccessToken(
config.accountSid, config.apiKey, config.apiSecret, {identity: 'SG'}
);
const grant = new VoiceGrant({
outgoingApplicationSid: config.appSid,
incomingAllow: true,
});
accessToken.addGrant(grant);
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({ token: accessToken.toJwt() }));
});
module.exports = router;
Twilio developer evangelist here.
How to answer the phone using the Twilio Device.
The device registers with no issue, so why doesn't it get incoming calls?
To direct a call to the Device, you need to return TwiML that <Dial>s the <Client> with the ID of your access token ("SG" in this case).
So, if you want calls to your Twilio number to be directed to this client you should update the Twilio number's incoming webhook to point to a URL that returns this:
<Response>
<Dial>
<Client>
<Identity>SG</Identity>
</Client>
</Dial>
</Response>
How to call other numbers aside from the one in my app.
I did in device.connect({params: {To: '+2222222222'}}), why doesn't it call that number?
Currently, it sounds like you point the Device to a TwiML app that responds with static TwiML that dials your example number '+11111111111'. To use the parameters, you will need to make that TwiML dynamic, by returning it from your Node server instead. The parameters are sent to the TwiML endpoint, so you can then use them in the response.
Here is an example Express endpoint that would work for you:
const express = require('express');
const router = express.Router();
const { VoiceResponse } = require("twilio").twiml;
const config = require('../config');
router.use(express.urlencoded({ extended: false }));
router.post("/call", function(res, res) {
const To = req.body;
const twiml = new VoiceResponse();
const dial = twiml.dial({ callerId: config.twilioNumber });
dial.number(To);
res.set("Content-Type", "text/xml");
res.send(twiml.toString());
});
module.exports = router;
I need track statusCallbackEvent when call answered, completed, also need to pass StatusCallback with custom parameter please suggest how to achieve it?
my code is something like
public CallResource MakeOutboundPhoneCallsAsync(OutgoingCallRequest request, string accountSid, string authToken)
{
try
{
TwilioClient.Init(accountSid, authToken);
List<string> statusCallbackEvent = new List<string> { "answered", "completed" };
CallResource response =
CallResource.Create(
url: new Uri("http://demo.twilio.com/docs/voice.xml"),
to: new PhoneNumber(request.ToPhoneNumber),
from: new PhoneNumber(request.FromPhoneNumber),
method: Twilio.Http.HttpMethod.Get,
statusCallback: new Uri("http://b28deaf4.ngrok.io/api/Twilio/OutboundCalls/StatusCallback"),
statusCallbackEvent: statusCallbackEvent,
statusCallbackMethod: Twilio.Http.HttpMethod.Post
);
return response;
}
catch (Exception e)
{
throw e;
}
}
Twilio developer evangelist here.
If you want to pass more parameters back to your application via the webhook, you can do so by including query parameters in the URL. For example:
statusCallback: new Uri("http://b28deaf4.ngrok.io/api/Twilio/OutboundCalls/StatusCallback?ExtraParameter=InTheQueryString"),
Then you can read them out of the URL when your application receives the request.
Sending a message from Twilio is succesful, now i want to be able to enter the TO phone number the message body from a form, but i'm not sure which method is the best. I'm thinking maybe calling a variable from another ViewController but i am not sure if that would work, suggestions?
Here is my twilio controller
public IActionResult Sendsms()
{
var accountSid = "XXXXXXXXXXXXXXXXXXXXXXXXXX";
var authToken = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
TwilioClient.Init(accountSid, authToken);
var to = new PhoneNumber("+XXXXXXXXXXXXXXX");
var from = new PhoneNumber("+XXXXXXXXXXXXXXXX");
var message = MessageResource.Create(to: to,
from: from,
body: "this is the ship that made the kessel run in 14 parsecs?");
return Content(message.Sid);
}
I implemented conference call in Twilio, but it doesn't work. The error is:
Error: 11200 HTTP retrieval failure
In more details :
405 - HTTP verb used to access this page is not allowed.
Code:
string AccountSid = "...";
string AuthToken = ".....";
var twilio = new TwilioRestClient(AccountSid, AuthToken);
string appversion = twilio.ApiVersion;
ArrayList participants = new ArrayList();
// participants.Add("+972599223072");
participants.Add(txtphone1.Text);
participants.Add(txtphone2.Text);
participants.Add(txtphone3.Text);
participants.Add(txtphone4.Text);
participants.Add(txtphone5.Text);
participants.Add(txtphone6.Text);
participants.Add(txtphone7.Text);
// Go through the participants array and call each person.
foreach (string user in participants)
{
if (user != "")
{
var options = new CallOptions();
options.Url = "http://sandbox4.eureeca.com/Conference/conference.xml";
options.To = user;
options.From = "+97243741357";
options.Method = "POST";
options.Record = true;
// options.StatusCallback = "/2010-04-01/Accounts/" + AccountSid + "/Calls";
var call = twilio.InitiateOutboundCall(options);
Console.WriteLine(call.Sid);
}
Code END
Conference.xml content :
<?xml version="1.0" encoding="utf-8" ?>
<Response>
<Say>Joining a conference room</Say>
<Dial>
<Conference>MyConference</Conference>
</Dial>
</Response>
Twilio evangelist here.
Looks like you're TwiML is in a static XML file? Its pretty common for web servers to not allow POST requests to static files. You can either reconfigure your web server to allow this, or change the CallOptions Method property to `GET' to tell Twilio to make a GET request for the file rather than a POST.
Hope that helps.