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.
Related
I'm creating a sample application that will post alerts to the website in the event of a hurricane or service outage. I'm not using Laravel.
I set the URL of the page in my account settings. The first time I sent a message I received a HTTP error that it had timed out without being given a reponse. I edited the XML and tried again.
I'm not getting anything in the database and I'm not getting the response. I also wrote a sample page that posts a value to see if it would work and it did. It posted it into the database and showed correctly formatted XML.
<?php
$response = 'This number cannot handle automated replies...';
$twiml1 = '<response><sms>';
$twiml2 = '</sms></response>';
require_once '../settings/db.php';
if (isset($_POST['body'])) {
$body = strip_tags($_POST['body']);
$sql = "INSERT INTO alerts (message) VALUES ('$body')";
$result = $db->query($sql);
if ($result) {
$response = 'Thanks. Your message was posted on the website.';
} else {
$response = 'There was a query error.';
}
}
header('Content-type: application/xml');
echo $twiml1;
echo $response;
echo $twiml2;
Twilio developer evangelist here.
Parameters that are sent via webhooks from Twilio are case sensitive and start with a capital letter. The text for an incoming message is sent as the Body parameter so checking for $_POST['body'] won't work.
I'd update your conditional to:
if (isset($_POST['Body'])) {
$body = strip_tags($_POST['Body']);
// The rest
}
Also, just to note, the <Sms> element has been deprecated. I'd use the <Message> element instead. The tags are case sensitive too, so I'd update the TwiML section to this:
$twiml1 = '<Response><Message>';
$twiml2 = '</Message></Response>';
Let me know if that helps at all.
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";
}
}
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.
I'm currently working on the imap class by barbushin. It's the only php class over the internet I can find regardless to any encoding issue. Thanks to the coder.
I have a list of messages in a table. Each message sending a message id as GET (say $mid). When a link clicked, the page turned into a view page. It should open that message and display the relevant content right? But it is not. Every message has the same content (the 1st content). The code is designed for gmail but I use it for my client. And it's work.
This is a code:
require_once('../ImapMailbox.php');
define('EMAIL', 'my#domain.com');
define('PASSWORD', '*********');
define('ATTACHMENTS_DIR', dirname(__FILE__) . '/attachments');
$mailbox = new ImapMailbox('{imap.gmail.com:993/imap/ssl}INBOX', EMAIL, PASSWORD, ATTACHMENTS_DIR, 'utf-8');
$mails = array();
// Get some mail
$mailsIds = $mailbox->searchMailBox('ALL');
if(!$mailsIds) {
die('Mailbox is empty');
}
$mailId = reset($mailsIds);
$mail = $mailbox->getMail($mailId);
var_dump($mail);
var_dump($mail->getAttachments());
The original is here: https://github.com/barbushin/php-imap
Finally, I found my way home. According to the script there's a line says "mailId". Which is straight forward what is it about.
It was set to the first array by reset(). So the only thing I need to do is extract the message id from it ($mailId is an array of ids). So I simply add an array behind it.
$mailId=$mailsIds[$_GET[uid]];
While $_GET[uid] is a message id sent from a previous page.
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').