Twilio API get SID of given number - php

I need to get SID of given number via API.
I am using this code and it works:
foreach ($client->account->incoming_phone_numbers->getIterator(0, 50, array(
"PhoneNumber" => $_SERVER['QUERY_STRING']
)) as $number
) {
$sid = $number->sid;
}
My question is I do not need this to be in a loop since there will only ever be one entry, so what is the singular of ->getIterator? I could use ->get but that requires the SID, which I don't have yet.

Megan from Twilio here.
In order to receive the Sid you must do within the loop. Here's an example from the incoming phone numbers API reference as you also show above.
foreach ($client->account->incoming_phone_numbers->getIterator(0, 50, array(
"PhoneNumber" => "+15555555555"
)) as $number
) {
echo $number->sid;
}
Let me know if this helps!

Maybe I have a totally different version of the php library. But the above didn't work at all for me.
I ended up accomplishing it like this...
$phoneNumber="+15551234567";
$twilio=new Client(TWILIO_ACC_ID,TWILIO_AUTH_TOKEN);
//get all the phone numbers on our account (assuming we won't have more than 1000 numbers)
$incoming_phone_numbers=$twilio->incomingPhoneNumbers->read([],1000);
//look for the one with our matching number and save the sid
foreach ($incoming_phone_numbers as $number) {
if ($number->phoneNumber==$phoneNumber) {
$thisSid=$number->sid;
break;
}
}
if ($thisSid) print("Found the SID for: ".$phoneNumber." It's: ".$thisSid);

Related

Twilio API PHP list available Phone numbers for purchase API Version 5.X

I am looking for a little assistance on listing available phone numbers for purchase using Twilios API and PHP for their 5.X API Verison. Below is the error I get and the PHP im using. Im sure im just overlooking something:
PHP Notice: Trying to get property of non-object in /twilio-php-app/findnumbers.php on line 16
PHP Warning: Invalid argument supplied for foreach() in /twilio-php-app/findnumbers.php on line 16
<?php
// Get the PHP helper library from https://twilio.com/docs/libraries/php
require_once 'vendor/autoload.php'; // Loads the library
use Twilio\Rest\Client;
// Your Account Sid and Auth Token from twilio.com/user/account
$sid = "Axxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$token = "removed";
$client = new Client($sid, $token);
$numbers = $client->availablePhoneNumbers('US')->local->read(
array("areaCode" => "513")
);
foreach($numbers->availablephonenumbers as $number) {
echo $number->phone_number;
}
If I echo $numbers I find it is an array. Here is the raw output where I just want to get the "phone_number": "xxxxxx" output; minus the "phone_number": part.
output of array Screenshot
Adding to this, if I run the PHP as the following; I get single number outputs
$numbers = $client->availablePhoneNumbers('US')->local->read(
array("areaCode" => "513")
);
echo $numbers[1]->phoneNumber;
Changing the value of [1] to [2] grabs the next phone number. How can I loop this?
Might not be done 100% correct but I found a solution that increases the count of the array based on count and stacks the numbers nicely.
Sharing this in case anyone else ever comes across this and needs help; this does exactly what its intended to.... Search the twilio databse for available numbers to purchase, based on criteria
<?php
// Get the PHP helper library from https://twilio.com/docs/libraries/php
require_once 'vendor/autoload.php'; // Loads the library
use Twilio\Rest\Client;
// Your Account Sid and Auth Token from twilio.com/user/account
$sid = "your_SID";
$token = "Your_Token";
$client = new Client($sid, $token);
$numbers = $client->availablePhoneNumbers('US')->local->read(
array("areaCode" => "513")
);
for ($i = 0; $i < count($numbers); ++$i) {
print $numbers[$i]->phoneNumber . "\n";
}
Just an observation, but you are already using the availablePhoneNumbers method on $client when you say $numbers = $client->availablePhoneNumbers...
Perhaps, in the foreach, you just need to reference $numbers and not $numbers->availablephonenumbers?

retrieve twilio transcription text in php without knowing sid

I am working on an twilio app which voice is transcribed and then converted to text. Everything is functional until it comes to retrieving the transcription text. I am aware I can retrieve transcription code if I know the "sid" but what if I want the transcription code on the fly and do not know the "sid". In other words I would like the newest transcription from phone number "555-555-1212" all I can find is the code below.
<?php
// Get the PHP helper library from twilio.com/docs/php/install
require_once('/path/to/twilio-php/Services/Twilio.php'); // Loads the library
// Your Account Sid and Auth Token from twilio.com/user/account
$sid = "AC1240edf87a1d3b6717472af6deda4ce7";
$token = "{{ auth_token }}";
$client = new Services_Twilio($sid, $token);
$client->account->transcriptions->delete("TR8c61027b709ffb038236612dc5af8723");
?>
Thanks in advance!
Diego
You are going to need to get the SID for the call, but that is easy enough to do if you know the phone number, and optionally a date range to look for (my PHP is rusty so you may need to touch this up):
// Your Account Sid and Auth Token from twilio.com/user/account
$sid = "{{ sid }}";
$token = "{{ auth_token }}";
$client = new Services_Twilio($sid, $token);
// Get calls to a number on or after a certain date.
foreach ($client->account->calls->getIterator(0, 50, array("Status" => "completed", "To" => "555-555-1212","StartTime" => "2013-10-26")) as $call) {
echo $call->sid
//now use the sid to get the transcription text using a seperate rest call.
$transcription = $client->account->transcriptions->get($call->sid);
echo $transcription->transcription_text;
}
Fix for my original question =)
<?php
//RETRIEVE NUMBERS LAST TRANSCRIPTION
$client = new Services_Twilio($sid, $token);
$i=0;
foreach($client->account->transcriptions->getIterator(0, 50, array('Status' => 'completed', 'To' => ''.$_GET['number'].'')) as $call) {
//now use the sid to get the transcription text using a seperate rest call.
if($i==1) break;
$transcription = $client->account->transcriptions->get($call->sid);
$sms_text = $transcription->transcription_text;
$i++;
}
?>
Twilio evangelist here.
Another option is if you are using the <Record> verb is to you can set the transcribeCallback parameter:
https://www.twilio.com/docs/api/twiml/record#attributes-transcribe-callback
This lets you give Twilio a URL that we will request when a transcription is completed.
Hope that helps.

Getting currency conversion data from Yahooapis now that iGoogle is gone

Up until yesterday I had a perfectly working budget organizer site/app working with iGoogle.
Through PHP, using the following little line
file_get_contents('http://www.google.com/ig/calculator?hl=en&q=1usd=?eur');
and similar I was able to get all I needed.
As of today, this is no longer working. When I looked into the issue, what has happened is that Google has retired iGoogle. Bummer!
Anyway, I was looking around elsewhere but I can't find anything that fits my needs. I would REALLY love to just fix it and get it running again by just switching this one line of code (i.e. changing the Google address with the address of some other currency API available) but it seems like none does.
The API from rate-exchange.appspot.com seems like it could be a iGoogle analog but, alas, it never works. I keep getting an "Over Quota" message.
(Here comes an initial question: anybody out there know of a simple, reliable, iGoogle-sort API?)
So I guess the natural thing would be to the Yahoo YQL feature (at least I suppose it is as reliable).
Yahoo's queries look like this:
http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ("USDEUR", "USDJPY", "USDBGN")&env=store://datatables.org/alltableswithkeys
What I really can't figure out is how to parse this data. It outputs an XML.
What I used to have is this:
function exchange($inputAmount,$inputCurrency,$outputCurrency) {
$exchange = file_get_contents('http://www.google.com/ig/calculator?hl=en&q='.$inputAmount.$inputCurrency.'=?'.$outputCurrency);
$exchange = explode('"', $exchange);
$exchange = explode('.', $exchange['3']);
$exchange[0] = str_replace(" ", "",preg_replace('/\D/', '', $exchange[0]));
if(isset($exchange[1])){
$exchange[1] = str_replace(" ", "",preg_replace('/\D/', '', $exchange[1]));
$exchange = $exchange[0].".".$exchange[1];
} else{
$exchange = $exchange[0];
}
return $exchange;
}
So the user was able to get the exchange rate from an input currency such as "USD" and an output currency such as "EUR" on a specific amount of money. As I said, this was working swimmingly up until yesterday night.
Any ideas?
Never mind! Solved it!
For anyone interested, here's what I did to get my code to work (with the least chnges possible) with the Yahoo YQL:
// ** GET EXCHANGE INFO FROM YAHOO YQL ** //
$url = 'http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ("USDEUR", "EURUSD")&env=store://datatables.org/alltableswithkeys'; //<-- Get the YQL info from Yahoo (here I'm only interested in converting from USD to EUR and vice-versa; you should add all conversion pairs you need).
$xml = simplexml_load_file($url) or die("Exchange feed not loading!"); //<-- Load the XML file into PHP variable.
$exchange = array(); //<-- Build an array to hold the data we need.
for($i=0; $i<2; $i++): //<-- For loop to get data specific to each exchange pair (you should change 2 to the actual amount of pairs you're querying for).
$name = (string)$xml->results->rate[$i]->Name; //<-- Get the name of the pair and turn it into a string (this looks like this: "USD to EUR").
$rate = (string)$xml->results->rate[$i]->Rate; //<-- Do the same for the actual rate resulting from the conversion.
$exchange[$name] = $rate; //<-- Put the data pairs into the array.
endfor; //<-- End for loop. :)
// ** WORK WITH EXCHANGE INFO ** //
$toeur = array( //<-- Create new array specific for conversion to one of the units needed.
'usd' => $exchange['USD to EUR'], //<-- Create an array key for each unit used. In this case, in order to get the conversion of USD to EUR I ask for it from my $exchange array with the pair Name.
'eur' => 1); //<-- The way I coded the app, I found it more practical to also create a conversion for the unit into itself and simply use a 1, which translates into "do not convert"
$tousd = array(
'eur' => $exchange['EUR to USD'],
'usd' => 1);
This is basically all you need to get all the exchange info you want. After that, you use it all something like this:
amount*$toxxx['coin'];
So, say I wanted to know how many Euro is 100 USD right now:
100*$toeur['usd'];
Piece of cake!
Still a very useful solution by QuestionerNo27. Since early 2015, however, Yahoo YQL apparently slightly changed the XML output of their api. 'Name' now no longer translates into a string like 'USD to EUR', but to 'USD/EUR' and should in the code above be referenced this way:
$toeur = array(
'usd' => $exchange['USD/EUR']
instead of
$toeur = array(
'usd' => $exchange['USD to EUR']
and in a similar fashion for other currency conversions.
I created a routine to convert the currency based on #QuestionerNo27 http://jamhubsoftware.com/geoip/currencyconvertor.php?fromcur=USD&tocur=EUR&amount=1 you can consume this
<?php
$fromcur = $_GET['fromcur'];
$tocur = $_GET['tocur'];
$amt = $_GET['amount'];
// ** GET EXCHANGE INFO FROM YAHOO YQL ** //
$url = 'http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ("'.$fromcur.$tocur.'")&env=store://datatables.org/alltableswithkeys'; //<-- Get the YQL info from Yahoo (here I'm only interested in converting from USD to EUR and vice-versa; you should add all conversion pairs you need).
$xml = simplexml_load_file($url) or die("Exchange feed not loading!"); //<-- Load the XML file into PHP variable.
$exchange = array(); //<-- Build an array to hold the data we need.
for($i=0; $i<2; $i++): //<-- For loop to get data specific to each exchange pair (you should change 2 to the actual amount of pairs you're querying for).
$name = (string)$xml->results->rate[$i]->Name; //<-- Get the name of the pair and turn it into a string (this looks like this: "USD to EUR").
$rate = (string)$xml->results->rate[$i]->Rate; //<-- Do the same for the actual rate resulting from the conversion.
$exchange[$name] = $rate; //<-- Put the data pairs into the array.
endfor; //<-- End for loop. :)
// ** WORK WITH EXCHANGE INFO ** //
$conv = $fromcur . '/' . $tocur;
$toeur = array( //<-- Create new array specific for conversion to one of the units needed.
$tocur => $amt*$exchange[$conv], //<-- Create an array key for each unit used. In this case, in order to get the conversion of USD to EUR I ask for it from my $exchange array with the pair Name.
$fromcur => $amt,
"ex_amt" =>$amt*$exchange[$conv]); //<-- The way I coded the app, I found it more practical to also create a conversion for the unit into itself and simply use a 1, which translates into "do not convert"
echo json_encode($toeur);
?>

How do I use the twilio-php library to retrieve all calls made between two dates?

Using the following code I am able to get the logs of calls and SMS's. How do I modify this code to only search between certain dates using PHP?
// Instantiate a new Twilio Rest Client
$client = new Services_Twilio($AccountSid, $AuthToken, $ApiVersion);
// http://www.twilio.com/docs/quickstart...
try {
// Get Recent Calls
foreach ($client->account->calls as $call) {
echo "Call from $call->sid : $call->from to $call->to at $call->start_time of length $call->duration $call->price <br>";
}
}
catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}
You will want to add a code snippet that looks something like this:
$client = new Services_Twilio('AC123', '123');
foreach ($client->account->calls->getIterator(0, 50, array(
'StartTime>' => '2012-04-01',
'StartTime<' => '2012-05-01'
)) as $call) {
echo "From: {$call->from}\nTo: {$call->to}\nSid: {$call->sid}\n\n";
}
If you want to filter the list, you have to construct the iterator yourself with the getIterator command. There's more documentation here: Filtering Twilio Calls with PHP
User search terms StartTime> and StartTime< for this. First one means call start time is greater than and last one means call start time is less than.
To find every calls that started between 4th and 6th July of 2009 add search term
array(
'StartTime>' => '2009-07-04',
'StartTime<' => '2009-07-06'
)
See example 4 on the twilio doc.
Also note you can always ask twilio support. They usually help gladly.

facebook api: count attendees for event (limit problem)

Okay normally I'm all fine about the facebook API but I'm having a problem which just keeps me wondering. (I think it's a bug (Check ticket http://bugs.developers.facebook.net/show_bug.cgi?id=13694) but I wanted to throw it here if somebody has an idea).
I'm usng the facebook PHP library to count all attendees for a specific event
$attending = $facebook->api('/'.$fbparams['eventId'].'/attending');
this works without a problem it correctly returns an array with all attendees...
now heres the problem:
This event has about 18.000 attendees right now.
The api call returns a max number of 992 attendees (and not 18000 as it should).
I tried
$attending = $facebook->api('/'.$fbparams['eventId'].'/attending?limit=20000');
for testing but it doesn't change anything.
So my actual question is:
If I can't get it to work by using the graph api what would be a good alternative? (Parsing the html of the event page maybe?) Right now I'm changing the value by hand every few hours which is tedious and unnecessary.
Actually there are two parameters, limit and offset. I think that you will have to play with both and continue making calls until one returns less than the max. limit.
Something like this, but in a recursive approach (I'm writting pseudo-code):
offset = 0;
maxLimit = 992;
totalAttendees = count(result)
if (totalAttendees >= maxLimit)
{
// do your stuff with each attendee
offset += totalAttendees;
// make a new call with the updated offset
// and check again
}
I've searched a lot and this is how I fixed it:
The requested URL should look something like this.
Here is where you can test it and here is the code I used:
function events_get_facebook_data($event_id) {
if (!$event_id) {
return false;
}
$token = klicango_friends_facebook_token();
if ($token) {
$parameters['access_token'] = $token;
$parameters['fields']= 'attending_count,invited_count';
$graph_url = url('https://graph.facebook.com/v2.2/' . $event_id , array('absolute' => TRUE, 'query' => $parameters));
$graph_result = drupal_http_request($graph_url, array(), 'GET');
if(is_object($graph_result) && !empty($graph_result->data)) {
$data = json_decode($graph_result->data);
$going = $data->attending_count;
$invited = $data->invited_count;
return array('going' => $going, 'invited' => $invited);
}
return false;
}
return false;
}
Try
SELECT eid , attending_count, unsure_count,all_members_count FROM event WHERE eid ="event"

Categories