Get twilio recording for each call record - twilio

It looks like all the guides are outdated on this matter, and twilio's website doesnt have a clear answer for this.
Im trying to get a list of all calls, and for each call record check for a recording record, if it has a recording record then get the uri for it.
Although I dont think this is the correct way of doing what im trying to do the script is very very slow, and doesnt work as expected , here is where im at right now :
// Set our AccountSid and AuthToken
$sid = 'MY_SID';
$token = 'MY_TOKEN';
// Your Account Sid and Auth Token from twilio.com/user/account
$client = new Client($sid, $token );
// Loop over the list of calls and echo a property for each one
foreach ($client->account->calls->read() as $call
) {
echo $call->sid.", ".getRecording($call->sid)."<br/>";
}
function getRecording($callsid){
// Set our AccountSid and AuthToken
$sid = 'MY_SID';
$token = 'MY_TOKEN';
$client = new Client($sid, $token);
// Loop over the list of recordings and echo a property for each one
foreach ($client->account->recordings->read( array( "CallSid" => $callsid )) as $recording ) {
return " ->".$callsid." <a href='http://api.twilio.com".$recording->uri."'>Audio</a> ";
}
}
The output is that all the recording URI are the same for each .
CAb5323eed7ed4f82b3990830777c02684, ->CAb5323eed7ed4f82b3990830777c02684 <a href='http://api.twilio.com/2010-04-01/Accounts/My_account_nr/Recordings/RE9f96dc253140ffdfa8cd37c139de978s.json'>Audio</a>
CA57df3525265949c4dfcaa9073b02880a, ->CA57df3525265949c4dfcaa9073b02880a <a href='http://api.twilio.com/2010-04-01/Accounts/My_account_nr/Recordings/RE9f96dc253140ffdfa8cd37c139de978s.json'>Audio</a>
CA31f0ac07483d72a56d424b55672a61ab, ->CA31f0ac07483d72a56d424b55672a61ab <a href='http://api.twilio.com/2010-04-01/Accounts/My_account_nr/Recordings/RE9f96dc253140ffdfa8cd37c139de978s.json'>Audio</a>
CAac6e6f0d45cd15069300202ce6cbc27e, ->CAac6e6f0d45cd15069300202ce6cbc27e <a href='http://api.twilio.com/2010-04-01/Accounts/My_account_nr/Recordings/RE9f96dc253140ffdfa8cd37c139de978s.json'>Audio</a>
CAe51db5d605b94c7141d43611bc8dbbd1, ->CAe51db5d605b94c7141d43611bc8dbbd1 <a href='http://api.twilio.com/2010-04-01/Accounts/My_account_nr/Recordings/RE9f96dc253140ffdfa8cd37c139de978s.json'>Audio</a>
CAbe46fe9ab0202fc15184915b0af94d1a, ->CAbe46fe9ab0202fc15184915b0af94d1a <a href='http://api.twilio.com/2010-04-01/Accounts/My_account_nr/Recordings/RE9f96dc253140ffdfa8cd37c139de978s.json'>Audio</a>
CA15c3eaccc8b1cfca648105744c1c1c8c, ->CA15c3eaccc8b1cfca648105744c1c1c8c <a href='http://api.twilio.com/2010-04-01/Accounts/My_account_nr/Recordings/RE9f96dc253140ffdfa8cd37c139de978s.json'>Audio</a>
CAcb9a5d1f7e3f3b4f3b1eff08f4e51094, ->CAcb9a5d1f7e3f3b4f3b1eff08f4e51094 <a href='http://api.twilio.com/2010-04-01/Accounts/My_account_nr/Recordings/RE9f96dc253140ffdfa8cd37c139de978s.json'>Audio</a>
CAfc6a986c4e58e35778d4242303f37e32, ->CAfc6a986c4e58e35778d4242303f37e32 <a href='http://api.twilio.com/2010-04-01/Accounts/My_account_nr/Recordings/RE9f96dc253140ffdfa8cd37c139de978s.json'>Audio</a>
CA58aa5dc00c72567b91b43db52577080a, ->CA58aa5dc00c72567b91b43db52577080a <a href='http://api.twilio.com/2010-04-01/Accounts/My_account_nr/Recordings/RE9f96dc253140ffdfa8cd37c139de978s.json'>Audio</a>
CA65dbdee33266a706f17616ecf03e78eb, ->CA65dbdee33266a706f17616ecf03e78eb <a href='http://api.twilio.com/2010-04-01/Accounts/My_account_nr/Recordings/RE9f96dc253140ffdfa8cd37c139de978s.json'>Audio</a>
Im looking for a better solution, because this doesnt work and this is also running very very slowly.

Twilio developer evangelist here.
You're right looping over all calls and then looping over all recordings of the call via a REST API is going to be very slow. I recommend that you do not take this approach in order to display the recordings.
Instead, there are two things that you can do.
Firstly, write a script similar to what you already have, but instead of writing out HTML, save the calls and their recordings to a database. That way, you can look through your own database which will be much quicker than making multiple calls to an API.
Secondly, rather than keep running that script to update for new calls, you can use recordingStatusCallbacks on calls. This allows you to set a webhook URL so that when a new call's recording is complete, your application will receive an HTTP request with all the information on the recordings. Then you can save that to your database too and your application will be kept updated with all the latest recordings.
Let me know if that helps.

This is actually a very quick and a great way.
Solution provided by a Twilio employee. Thanks
$client = new Client($sid, $token);
// Create an array of recordings
$recording_array = array();
// Loop over the list of recordings and echo a property for each one
foreach ($client->recordings->read() as $recording) {
$recording_array[$recording->callSid][$count] = $recording->sid;
$count++;
}
foreach ($client->account->calls->read() as $call) {
// Check if there is a call sid exist
if(array_key_exists($call->sid, $recording_array)){
foreach($recording_array["$call->sid"] as $key=>$val){
echo $call->sid.", Recording is ".$val."\r\n";
}
} else {
echo $call->sid."\r\n";
}
}

Related

How to record-from-answer-dual with Twilio's object oriented interface?

I understand how to enable the 'record-from-answer-dual' with the XML style command set, but I'm not finding any way to accomplish the same thing with the more object-oriented style code, such as:
<?php
require_once 'twilio-php-master/Twilio/autoload.php';
$response = new Twilio\Twiml();
$sayMsg = 'Attention! Attention! The network operations
center has opened a ticket concerning an ATMS failure in the Eastern
region. The ticket number is ECHO,1,5,7,4. I repeat, the ticket number is
ECHO,1,5,7,4. Thank you.';
$response->record();
$response->say($sayMsg, array('voice' => 'alice'));
$response->hangup();
echo $response;
I've tried adding it to the new line, and the record line as an array-style entry, similar to enabling the Alice voice. No dice.
I want to record the entire call, from answer, including the message spoken by Twilio.
Thanks for any information anyone can provide!
Twilio developer evangelist here.
<Record> is used to record messages from a call, not to record the TwiML that follows. It's more useful if you are building a messaging or voicemail system for voice.
Given that your message sounds like some kind of announcement, I am guessing that you are generating this call from the REST API. In that case, you can use the Record parameter when you place the call and the entire call will be recorded. In PHP, that would be something like this:
require_once '/path/to/vendor/autoload.php';
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(
$to, $from,
array(
"url" => $url,
"record" => true
)
);
Check out the documentation on the parameters you can use when making a call, including Record here.
Let me know if that helps at all.
Update from Jeffrey's comment
This is the Perl version, using the unofficial Twilio Perl module:
use WWW::Twilio::API;
my ($twilaccountsid, $twilauthtoken, $fromnum, $tonum, $twiml_uri) = #_;
my $twilio = WWW::Twilio::API->new(AccountSid => $twilaccountsid, AuthToken => $twilauthtoken);
my $response = $twilio->POST( 'Calls', From => $fromnum, To => $tonum, Record => 'true', Url => $twiml_uri);
return $response->{content};

How can I record incoming calls on Twilio?

I have a website that uses Twilio to allow people to use our temporary numbers to receive SMS messages received during verification processes etc. It is becomming more common that companies are switching to audio verification instead so I want to start recording all calls received and displaying them in the existing HTML table using the HTML5 <audio> tag.
Here is the existing code:
<tbody>
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Get the PHP helper library from twilio.com/docs/php/install
require_once('twilio/Services/Twilio.php'); // Loads the library
// Your Account Sid and Auth Token from twilio.com/user/account
$sid = "";
$token = "";
$client = new Services_Twilio($sid, $token);
$messages = $client->account->messages->getIterator(0, 50, array(
'To' => $_SERVER['QUERY_STRING'] // this is the number
));
foreach ($messages as $message) {
echo "<tr><td>" . $message->from . "</td><td>" . $message->date_sent . "</td><td>" . $message->body . "</td></tr>";
}
?>
</tbody>
</table>
How can I build in to that the recorded calls received? I want to keep it in date/time order within the eixsting SMS messages, if that makes sense.
Twilio developer evangelist here.
You can absolutely record calls with Twilio.
When you create a call, you just need to include the parameter Record=true in the REST API request to create a call. Then, if you include a statusCallback parameter that points to a URL on your server, then you will receive a webhook to that URL when the call is complete that includes a link to the recording.
You can also fetch the latest recordings from the API. You can get recordings in wav or mp3 format, which you can then use in the HTML <audio> element.
I'm not sure how you have set up your date ordered SMS table, but hopefully this helps. Let me know if there is anything else I can help with.

Twilio REST API How to get Sid

I am still new to Twilio. I am writing a PHP script which will connect to Twilio and parse some information about calls. I am using the code from this page:
https://www.twilio.com/docs/api/rest/call
Here is my code:
require_once '../twilio-library/Services/Twilio.php';
// Twilio REST API version
$version = '2010-04-01';
// Set our AccountSid and AuthToken
$sid = 'abc132xxxxx';
$token = 'xxxxeeffv';
// Instantiate a new Twilio Rest Client
$client = new Services_Twilio($sid, $token, $version);
// Loop over the list of calls and echo a property for each one
foreach ($client->account->calls as $call) {
echo "->".$call->Sid."<- <br/>";
}
The browser just outputs many blanks. No Sid values. What am I doing wrong?
Twilio Developer Evangelist here.
Try doing the following to get call information.
<?php
require_once '../twilio-library/Services/Twilio.php';
// Your Account Sid and Auth Token from twilio.com/user/account
$sid = 'abc132xxxxx';
$token = 'xxxxeeffv';
$client = new Services_Twilio($sid, $token);
// Loop over the list of calls and echo a property for each one
foreach ($client->account->calls as $call) {
echo $call->sid;
}
Notice that if you're using the latest version of the library, you don't need to specify a version on your request. Double check that the path ../twilio-library/Services/Twilio.php is correct for you though.
If you're only testing, you could move the file Twilio.php to the same directory where your code is and just import Twilio.php on it.
If you then decide to filter the logs by date, here's how you would do it.
// Loop over the list of calls and echo a property for each one
foreach ($client->account->calls->getIterator(0, 50, array(
"Status" => "completed",
"StartTime>" => "2015-03-01",
"StartTime<" => "2015-05-10"
)) as $call
) {
echo $call->sid;
}
Let me know how it goes.

Twilio -- How to get link to media file sent via MMS?

I am using $messages = $client->account->sms_messages->getIterator(0, 50, array()); and variations thereof to get the text from txt messages.
However, when the message is an image the result is blank.
How do I go about getting the link to the media? I would prefer it not be displayed inline but rather as a link such as "Click here for media." and then open a new window to the image, audio, video, etc.
Ricky from Twilio here.
If you want to access the url of the media for a message you would use this code:
$client = new Services_Twilio($AccountSid, $AuthToken);
foreach ($client->account->messages->getIterator(0, 50, array()) as $message) {
foreach ($message->media as $media) {
echo "http://api.twilio.com" . $media->uri;
}
}
In this code access the media subresources for our message and then loop over them. I'm just echoing the results but you could do whatever you'd like with this data.

Using Twitter OAuth to authenticate API calls for trends

I am working on a website that allows the user to search for the top ten twitter trends in a city or country. At first I was only relying on Twitter's Rest API, but I was having a lot of rate limit issues (at school my rate limit disappears faster than I have a chance to use it). I know that authenticating my API calls will help me to better deal with this issue (Authenticated API calls are charged to the authenticating user’s limit while unauthenticated API calls are deducted from the calling IP address’ allotment).
I implemented #abraham's PHP library (https://github.com/abraham/twitteroauth), unfortunately my API calls aren't being authenticated. I know I have implemented #abraham's PHP library, because it prints out my user information at the end like it should. I have my twitter trend search underneath it but the API call isn't being authenticated. I am not sure how to fix this, and any help would really be appreciated!
This is what I use to get the top ten trends by country:
function showContent(){
// we're going to point to Yahoo's APIs
$BASE_URL = "https://query.yahooapis.com/v1/public/yql";
// the following code should only run if we've submitted a form
if(isset($_REQUEST['location']))
{
// set a variable named "location" to whatever we passed from the form
$location = $_REQUEST['location'];
// Form YQL query and build URI to YQL Web service in two steps:
// first, we show the query
$yql_query = "select woeid from geo.places where text='$location'";
// then we combine the $BASE_URL and query (urlencoded) together
$yql_query_url = $BASE_URL . "?q=" . urlencode($yql_query) . "&format=json";
//var_dump($location);
// show what we're calling
// echo $yql_query_url;
// Make call with cURL (curl pulls webpages - it's very common)
$session = curl_init($yql_query_url);
curl_setopt($session, CURLOPT_RETURNTRANSFER,true);
$json = curl_exec($session);
// Convert JSON to PHP object
$phpObj = json_decode($json);
// Confirm that results were returned before parsing
if(!is_null($phpObj->query->results)){
// Parse results and extract data to display
foreach($phpObj->query->results as $result){
//var_dump($result);
$woeid = $result[0]->woeid;
if (is_numeric ($location))
{
echo "<span style='color:red; padding-left: 245px;'>Please enter a city or a country</span>";
}
else if(empty($result)){
echo "No results found";
}
else {
/* echo "The woeid of $location is $woeid <br />"; */
}
}
}
$jsontrends=file_get_contents("http://api.twitter.com/1/trends/".$woeid.".json");
$phpObj2 = json_decode($jsontrends, true);
echo "<h3 style='margin-top:20px'>TRENDS: ".$phpObj2[0]['locations'][0]['name']."</h3> \r\n";
$data = $phpObj2[0]['trends'];
foreach ($data as $item) {
echo "<br />".$item['name']."\r\n";
echo "<br /> \r\n";
}
if(empty($item)){
echo "No results found";
}
}
}
I then add it to #abraham's html.inc file (along with some php to see the rate limit status) and html.inc is included in the index.php:
<h1>Top Twitter Trends</h1>
<form name='mainForm' method="get">
<input name='location' id='location' type='text'/><br/>
<button id='lookUpTrends'>Submit</button>
</form>
<?php showContent();
$ratelimit = file_get_contents("http://api.twitter.com/1/account/rate_limit_status.json");
echo $ratelimit;
?>
</div>
#abraham's index.php file has some example calls, and since my call doesn't look like this I think that is probably why it isn't being authenticated.
/* Some example calls */
//$connection->post('statuses/update', array('status' => date(DATE_RFC822)));
//$connection->post('statuses/destroy', array('id' => 5437877770));
//$connection->post('friendships/create', array('id' => 9436992));
//$connection->post('friendships/destroy', array('id' => 9436992));
Please help me find what I need to fix so that my API calls are authenticated.
update 10-21
I think in order to make an authenticated API call I need to include something like this is my code:
$connection->get('trends/place', array('id' => $woeid));
It didn't fix my problem, but maybe it is on the right track?
First off, you'll find that keeping your PHP and HTML separate will really help streamline your code and keep logical concerns separate (aggregating the data and displaying it are two different concerns)(many PHPers like MVC).
The code you have shared appears to be correct. My guess is that the issue lies in the creation of the OAuth connection, which should look something like:
<?php
/* Create TwitteroAuth object with app key/secret and token key/secret from default phase */
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $token,$secret);
Where CONSUMER_KEY and CONSUMER_SECRET are from your Trends Test app and $token and $secret are from the user signing in to twitter and allowing your app permission. Are all these values showing up when you create the TwitterOAuth object?
Also, be sure you update the config items in the twitteroauth.php file (specifically line 21 should be set to use the 1.1 API and line 29 should be set to 'json').

Resources