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.
Related
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?
I hope you can help me with an issue with phone call dialings using Plivo PHP (new SDK 4.0). First I will indicate what I want to achieve:
- A client on my website wants to talk with an agent of main, so he introduces his telephone number in a form, choose an agent, and finally when submit, the website connect both of them dialing (this works). But then, (here begin my problems), I can't retrieve the call details (status, duration, initial and end dates of the call, etc...) for invoicing the client according to some of these details.
Edited 2018/02/23:
Ramya, the 600 error has dissapeared and everything seems to be ok as I see in the Plivo debug log. Below are my new codes (I think better done thanks to your instructions), and then, I show you the Plivo debud log (perhaps it's better you can see it inside my account, call made Feb 23, 2018 18:33:15), and finally I see my server debug error log is empty!.
The main problem is that dialstatus.php file, although seems to receive the parameters, I don't know how to access them because dialstatus.php does not execute showing the data in my monitor (in my code for example, this line never shows in the monitor screen:)
echo "Status = $estado, Aleg UUID = $aleg, Bleg UUID = $bleg";
So even though it receives the parameters, I can not access them to manipulate them, print them on the screen, do ifs with them, etc. May it be perhaps a permission problem with the files? (These php files have 6,4,4 permissions on my server, the same as the others).
Thank you!
Code 1: makecall.php
require 'vendor/autoload.php';
use Plivo\RestClient;
$client = new RestClient("**********", "**************************");
$telefono_cliente = "34*******";
$telefono_experto = "34*********";
$duracion = 50;
try {
$response = $client->calls->create(
"3491111111",
[$telefono_experto],
"https://www.ejemplo.com/llamar/response.php?telf=$telefono_cliente",
'POST',
[
'time_limit' => $duracion,
]
);
$id = $response->requestUuid;
echo "<br>Este es el requestUuid: " . $id . "<br><br>";
}
catch (PlivoRestException $ex) {
print_r($ex);
}
?>
Code 2: response.php
require 'vendor/autoload.php';
use Plivo\XML\Response;
$resp = new Response();
$params = array(
'callerId' => '3491111111',
'action' => "https://www.ejemplo.com/llamar/dialstatus.php",
'method' => "POST",
'redirect' => "false"
);
$body3 = 'Desde ejemplo un cliente desea hablar con usted.';
$params3 = array(
'language' => "es-ES", # Language used to read out the text.
'voice' => "WOMAN" # The tone to be used for reading out the text.
);
$resp->addSpeak($body3,$params3);
$dial = $resp->addDial($params);
//$number = "34**********";
$number = $_GET['telf'];
$dial->addNumber($number);
Header('Content-type: text/xml');
echo($resp->toXML());
/*
Output:
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Speak language="es-ES" voice="WOMAN">Desde ejemplo un cliente desea hablar con usted.</Speak>
<Dial redirect="false" method="POST" action="http://www.ejemplo.com/llamar/dialstatus.php" callerId="3491111111">
<Number>34********</Number>
</Dial>
</Response>
*/
?>
Code 3: dialstatus.php
// Print the Dial Details
$estado = $_REQUEST['DialStatus'];
$aleg = $_REQUEST['DialALegUUID'];
$bleg = $_REQUEST['DialBLegUUID'];
echo "Status = $estado, Aleg UUID = $aleg, Bleg UUID = $bleg";
?>
Plivo Sales Engineer here.
Redirect = true is used only when you want to continue the call by returning another XML in your action URL. For you use case, you don't have to use this parameter. Even if the Redirect is set to false, Plivo will make a request to the action URL with a list of parameters. I looked into your account (here) and I can see this request getting sent with DialStatus, ALegUUID, BLegUUID along with other parameters.
Dial Action URL is the best place to know the DialStatus and DialHangupCause.
You can find the call duration and billing amount in Hangup URL request as well. This Hangup URL can be configured in your first API call (to the expert). By default, hangup URL is set to Answer URL.
Please raise a support ticket with us for further assistance.
I've been trying to post an image with a simple message onto twitter using PHP and twitteroauth.php.
However, every time I run my code, I only get the $tweetMessage published on the twitter feed without any image.
I searched and searched and read their own documentation but don't even get me started on their own documentation! its like someone who's had a sleepwalk was writing their documentation. Just a bunch of jargon..
And most of the information on STO is either outdated or pointing to a library!
I do not want to use any library as I will have to try to learn someone else's code as well and Surely twitter would allow publishing photo's using their own API without the use of any third party Library?!
Any way, This is my full code:
// Include twitteroauth
require_once('inc/twitteroauth.php');
// Set keys
$consumerKey = 'xxxxxxxxxxxxxxxxxxx';
$consumerSecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$accessToken = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$accessTokenSecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
// Create object
$tweet = new TwitterOAuth($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);
// Set status message
$tweetMessage = 'This is a tweet to my Twitter account via PHP.';
$image_path="https://www.google.co.uk/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
$handle = fopen($image_path,'rb');
$image = fread($handle,filesize($image_path));
fclose($handle);
// Check for 140 characters
if(strlen($tweetMessage) <= 140)
{
// Post the status message
$tweet->post('statuses/update', array('media[]' => "{$image};type=image/jpeg;filename={$image_path}", 'status' => $tweetMessage));
}
Could someone please advise on this issue?
Thanks in advance.
EDIT:
I've changed my code to the following and I get this error:
{"errors":[{"code":195,"message":"Missing or invalid url parameter."}]}
But I'm sure the image is on the specified URL/directory!
This is the code:
require_once 'inc/twitteroauth.php';
define("CONSUMER_KEY", "xxxxxxxxxxxxxxxxx");
define("CONSUMER_SECRET", "xxxxxxxxxxxxxxxxxxxxxxxxxx");
define("OAUTH_TOKEN", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
define("OAUTH_SECRET", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_SECRET);
$content = $connection->get('images/sign-in-with-twitter-l.png');
$image = 'images/sign-in-with-twitter-l.png';
$status_message = 'Attaching an image to a tweet';
$status = $connection->post('statuses/update_with_media', array('status' => $status_message, 'media[]' => file_get_contents($image)));
echo json_encode($status);
Any idea why this error is being shown?
Uploading media to Twitter is slightly complicated. Essentially, it's a three stage process.
Upload the photo to Twitter.
Receive a media_id back from Twitter.
Post your status and media_id to Twitter.
This is described in great detail at https://dev.twitter.com/rest/reference/post/media/upload
Generally speaking, it is easier for use to use a library like CodeBird as they've already done the hard work of finding all the edge cases.
But, assuming you don't want to do that...
POST the image to /1.1/media/upload.json
Receive back some JSON like
{
"media_id": 553656900508606464,
"media_id_string": "553656900508606464",
"size": 998865,
"image": {
"w": 2234,
"h": 1873,
"image_type": "image/jpeg"
}
}
* Use that media_id_string when you post the status. e.g.
tweet->post('statuses/update', array('media_ids' => $media_id_string, 'status' => $tweetMessage));
Hopefully that gives you enough to understand what's going on.
I solved it like this:
$tweet_img = 'Path/to/image';
$handle = fopen($tweet_img,'rb');
$image = fread($handle,filesize($tweet_img));
fclose($handle);
$parameters = array('media[]' => "{$image};type=image/jpeg;filename={$tweet_img}",'status' => 'Picture time');
$returnT = $connection->post('statuses/update_with_media', $parameters, true);
Horrible twitter API documentation needs improving!! it needs to be written by humans as opposed to a bunch of sleepwalking zombies!!!
This is a very frustrating situation that they put us in when we try to use their API...
They either need stop their API support and remove it all from the public or simply improve their documentation and write it for the public and not just for their own use using jargon words.
Any way, the above code works just fine using the latest twitteroauth
I hope this helps others in my situation.
I feel like i wasted 5 hours for something that should be clear and mentioned in plain English on their site!!!
Rant and Answer over & good luck.. :)
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);
I'm trying to work with the examples on the Twitter dev site but can't seem to get to the same signature as they have.
I am trying to complete step 3 on https://dev.twitter.com/docs/auth/implementing-sign-twitter because I am getting an error "Invalid or expired token" but I know it isn't because I've only just been given it, so it must be something wrong with my data packet.
The code I am using to try and generate this is:
// testing bit
$oauth = array(
'oauth_consumer_key'=>'cChZNFj6T5R0TigYB9yd1w',
'oauth_nonce'=>'a9900fe68e2573b27a37f10fbad6a755',
'oauth_signature_method'=>'HMAC-SHA1',
'oauth_timestamp'=>'1318467427',
'oauth_token'=>'NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0',
'oauth_version'=>'1.0'
);
$this->o_secret = 'LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE';
$this->c_secret = 'kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw';
ksort($oauth);
$string = rawurlencode(http_build_query($oauth));
$new_string = strtoupper($http_method).'&'.rawurlencode($main_url[0]).'&'.$string;
// The request_token request doesn't need a o_secret because it doesn't have one!
$sign_key = strstr($fullurl,'request_token') ? $this->c_secret.'&' : $this->c_secret.'&'.$this->o_secret;
echo urlencode(base64_encode(hash_hmac('sha1',$new_string,$sign_key,true)));exit;
And I'm assuming that the keys listed on this page are in fact correct: https://dev.twitter.com/docs/auth/creating-signature. So in that case the signature should be 39cipBtIOHEEnybAR4sATQTpl2I%3D.
If you can spot what I'm missing that would be great.
Your consumer secret and token secret are incorrect for the page you reference. If you look further up the page you can see that they should be:
Consumer secret: L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg
Token secret: veNRnAWe6inFuo8o2u8SLLZLjolYDmDP7SzL0YfYI
Also in Step 3 you need to include the oauth_verifier in the list of parameters when calculating your signature base string.
I'm not familiar with PHP so I haven't checked your code to calculate the signature.
This code has now worked - I will tidy it up from there :)
// This function is to help work out step 3 in the process and why it is failing
public function testSignature(){
// testing bit
$oauth = array(
'oauth_consumer_key'=>'cChZNFj6T5R0TigYB9yd1w',
'oauth_nonce'=>'a9900fe68e2573b27a37f10fbad6a755',
'oauth_signature_method'=>'HMAC-SHA1',
'oauth_timestamp'=>'1318467427',
'oauth_token'=>'NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0',
'oauth_version'=>'1.0'
);
$this->o_secret = 'LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE';
$this->c_secret = 'kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw';
ksort($oauth);
$string = http_build_query($oauth);
$new_string = strtoupper($http_method).'&'.$main_url[0].'&'.$string;
$new_string = 'POST&https%3A%2F%2Fapi.twitter.com%2F1%2Fstatuses%2Fupdate.json&include_entities%3Dtrue%26oauth_consumer_key%3Dxvz1evFS4wEEPTGEFPHBog%26oauth_nonce%3DkYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1318622958%26oauth_token%3D370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb%26oauth_version%3D1.0%26status%3DHello%2520Ladies%2520%252B%2520Gentlemen%252C%2520a%2520signed%2520OAuth%2520request%2521';
// The request_token request doesn't need a o_secret because it doesn't have one!
$sign_key = $this->c_secret.'&'.$this->o_secret;
echo 'Should be: tnnArxj06cWHq44gCs1OSKk/jLY=<br>';
echo 'We get: '.base64_encode(hash_hmac('sha1',$new_string,$sign_key,true));
exit;
}
you want to access token from twitter and sign in implementation you can see in this example.
1) http://www.codexworld.com/login-with-twitter-using-php/
and this one for timeline tweets
2) http://www.codexworld.com/create-custom-twitter-widget-using-php/
may be this help you .