Get tweet by ID with Twitter::Net - perl

I have a most simple task: I try to read programmatically a tweet given its ID. For the access to the Twitter API, I use Perl's Twitter::Net API .
In lack of a clear documentation of which methods Twitter::Net provides (the docu is very verbose on the search method, as if that would be the only method of interest, but it doesn't even provide a list of all supported methods), I had to work with trial and error.
Twitter's REST API doc says:
GET statuses/show/:id - returns a single Tweet, specified by the id
parameter. The Tweet's author will also be embedded within the tweet.
I create a Twitter::Net instance, using my credentials and the REST 1.1 trait,
my $nt = Net::Twitter->new(
traits => [ qw/API::RESTv1_1/ ],
consumer_key => '...',
consumer_secret => '...',
access_token => '...',
access_token_secret => '...',
ssl => 1
);
Now I tried
my $t = $nt->show( <tweet_id> );
with no success:
Tweets11.pm: Can't locate object method "show" via package "Net::Twitter_v4_01002_with__API_RESTv1_1__OAuth" at Tweets11.pm line 25.
Similar message with statuses instead of show.
How to afford this very simple task with Perl's Twitter::Net?

Per the docs for Twitter::Net, the method you want is actually show_status:
show_status
show_status(id)
Parameters: id, trim_user, include_entities, include_my_retweet
Required: id
Returns a single status, specified by the id parameter. The status's author will be returned inline.
Returns: Status

Related

Does tweet_mode=extended work with the Twitter statuses/user_timeline API?

There is no mention of tweet_mode at https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline.html
I am wondering if perhaps I am using the wrong API to be able to take advantage of tweet_mode?
In my application, I supplied the tweet_mode=extended argument and it had no effect. My code...
// Load the Tweets.
$args = array(
'screen_name' => $username,
'exclude_replies' => 'true',
'include_rts' => 'true',
'tweet_mode' => 'extended',
'count' => $numitems,
);
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
$tweets = $connection->get('statuses/user_timeline', $args);
if (!empty($tweets)) {
foreach ($tweets as $tweet) {
$text = $tweet->full_text;
// etcetera
Yes, you can use tweet_mode with the statuses/user_timeline API. Retweets are a special case, though. Check the retweeted_status object, as described at https://dev.to/kehers/formatting-tweets-a-look-at-extended-tweets-retweets-and-quotes-n5j
In short, if a tweet is a retweet, the extended tweet must be accessed at $tweet->retweeted_status->full_text. Thus, it's necessary in your code to check if each tweet object has a retweeted_status property.

CakePHP RESTful API routing with custom querystring params

I'm using CakePHP 2.x for a RESTful API, I want to be able to handle requests in the following form
api/activity/17?page=1&limit=10
Typically CakePHP I think likes each param to be separated by the forward slash char and then each of these is mapped into the variables defined in the 2nd array argument of router::connect above. For exampple:
api/activity/17/1/10
In my case though this won't work so I am trying to pass a custom query string which I will then decode in my controller. My router connect is as follows:
So I am using router::connect as follow:
Router::connect('/api/activity/:queryString', [
'controller' => 'users',
'action' => 'activity',
'[method]' => 'GET',
'ext' => 'json',
],
[
'queryString' => '[0-9]+[\?]...[not complete]'
]);
I can't get the regular expression to accept the '?' which I am exscaping in the regex above. How can I achieve this or otherwise is there a better or easier way of sending the URL in the format I require.
You can get the URL parameters (among other methods) via $this->request->query;
So, in your example, add the following in method view() of app/Model/Activity.php:
<?php
// file app/Model/Activity.php
public function view($id)
{
// URL is /activity/17?page=1&limit=10
echo $this->request->query['page']; // echo's: 1
echo $this->request->query['limit']; // echo's: 10
}
See 'Accessing Querystring parameters' in the CakePHP book

How to use new_direct_message with Net::Twitter::Lite

I'm trying to use in a script some DM functionalities and request.
My goal is on an event, sending a DM to a chosen follower.
For now, my working code is like this:
#!/usr/bin/perl
use strict;
use warnings;
use Net::Twitter::Lite::WithAPIv1_1;
my $twitter = Net::Twitter::Lite::WithAPIv1_1->new(
access_token_secret => 'XXX',
consumer_secret => 'XXX',
access_token => 'XXX',
consumer_key => 'XXX',
user_agent => 'Myself',
ssl => 1,
);
my $user = 'myself';
my $message_ack = "Hasta la vista, baby";
print "[sending: '$message_ack' to '$user'\n";
my $ack = $twitter->new_direct_message($user, $message_ack);
I have the following return:
# perl test.pl
[sending: 'Hasta la vista, baby' to 'myself'
new_direct_message expected 1 args at test.pl line 21.
I don't get is as the CPAN doc states that the 2 parameters given are required:
new_direct_message(user, text)
Parameters: user, text, screen_name, user_id, include_entities
Required: user, text
Sends a new direct message to the specified user from the
authenticating user. Requires both the user and text parameters.
Returns the sent message when successful. In order to support numeric
screen names, the screen_name or user_id parameters may be used
instead of user.
Returns: DirectMessage
Any hints on this one?
I've tried to google a bit on this, and I've found nothing really helpful. On some examples, they use the exact same thing as me (here for example: http://www.sevagas.com/Real-time-system-alerts-using-Twitter-OAuth-implementation on line 85)
I just figured it out with toolic comment.
So, there's the answer if someone ever have the same mistake :
Don't use
$twitter->new_direct_message($user, $message_ack);
but
$twitter->new_direct_message({ user => $user, text => $message_ack });
It looks like you have to pass a hashref, but I couldn't clearly see that hint in the doc.

How can I get attributes from complex SOAP::DATA structure in SOAP::Lite?

I can't get a simple attribute value from SOAP response using SOAP::Lite.
Below the code and output of SOAP::Data. I'm trying to get value of the attribute //response/dirn/attr/uuid
my $cm = new SOAP::Lite
uri => 'http://www.cisco.com/AXL/API/1.0',
proxy => "https://10.0.0.1:8443/axl/";
my $res = $cm->getPhone(
SOAP::Data->name(phoneName => 'SEP00270D3D7A4C'),
);
for my $i ($res->valueof('//device/lines/line')) {
print Dumper($i);
#print $i->{dirn}->{attr}->{'uuid'}."\n"; # line below give me an error
}
Here the output of Data::Dumper. I actually have the requested value, but I can't get it through SOAP::Data
$VAR1 = \bless( {
'_signature' => [],
'_value' => [
bless( {
'_name' => 'dirn',
'_signature' => [],
'_value' => [
''
],
'_prefix' => '',
'_attr' => {
'uuid' => '{615C3550-1EFD-56C7-3788-2AA8725880E3}' #!!!!!!!!!!!!!!!!!!!!!!!!!!
}
}, 'SOAP::Data' ),
],
'_attr' => {}
}, 'SOAP::Data' );
I spent about several hours trying to get this attribute value. I've already thinking about using output of Data::Dumper to get the value as fast and dirty hack.
Thanks in advance
P.S.: SOAP Server is Cisco CUCM 6.1.5
$$i->value->attr->{uuid}
$i->{'_value'}[0]{'uuid'}
I think, though, I'm not sure about the [0].
I have same issue, but can not find an "quick and easy" solution to it. I developed a Perl library module to use certain vendor Web Service (WSDL). I had done many of such Web Service interfaces, but until now - all of the data was returned as XML "elements". On the contrary, this particular Web Service returns most of the data as XML elements, but also sets some - as XML attributes. I can not get values returned as attributes - since SOAP::Data methods (valueof(), body(), etc.) only return values of XML elements, but not associated attributes.
This problem is a little different from the one posted before - in that I do not know up front the XML structure that is being returned (given web service provides many different methods, and each - has different response).
So question is - how it is possible to get all of the XML data (both elements and attributes) for a generic response SOAP data
I went through the same thing recently and found the answer, refer to my question and my updated answer in the comments section.
Extract specific XML element in CDATA taken from SOAP::Lite Response Hash

How to handle the big int facebook uid returned by FQL?

I've a problem in handling the big userid's of facebook and properly storing them into my database..
As the fql.query REST api is going to be deprecated ,I'm using the GRAPH API for getting the results of the FQL.
I want to get the list of my friends with sex,relationship_status .
The query i executed is
$allFriends = $facebook->api("/fql
?q=SELECT+uid,+name,+sex,+relationship_status+FROM+user+where+uid+in+
(SELECT+uid2+FROM+friend+WHERE+uid1+=$fbuid)"
);
I tried the above in the Graph API explorer and the result is something like this,
{
"data": [
{
"uid": 100003082853071,
"name": "Sam jones",
"sex": "male",
"relationship_status": null
}
]
}
Note the uid is returned as int, so whenever i print the array itself it has values like (1.34234422 +E03). So even json_encode for that array doesn't help.
But when i call the GRAPH API directly something like 'graph.facebook.com/1585213/friends' that returns the data as
{
"data": [
{
"name": "Vijay Kannan",
"id": "102937142343"
}
]
}
Note the id is returned as string..
Whenever I'm using the graph API call for FQL query, it returns the whole data as an 'Array' ,so the long big facebook uid's are transformed to a float like (1.34234422 +E03) .
How can i convert them into proper uid's and store/process them back.
I think the inconsistency of FQL and GRAPH API call should be also taken care by Facebook .. But i could not wait for that!!
Any ideas on this?
I tried most methods and after Google some more forums and facebook code list if found the following worked like a charm for me.
After i get the results from a FQL query i used the following line of code,
$friends = json_decode(preg_replace('/"uid":(\d+)/', '"uid":"$1"', $result),true);
// consider $result as the result rendered by the FQL query.
When i use the file_get_contents for a FB call you could have seen the error with error codes, so the best way to go with that is using CURL for all the FB API calls whenever necessary.
Please find the complete code i've used to get proper results,
$access_token = $facebook->getAccessToken();
$request_url ="https://graph.facebook.com/fql
?q=SELECT+uid,+name,+sex+FROM+user+where+uid+in+
(SELECT+uid2+FROM+friend+WHERE+uid1+=$fbuid)".
"&access_token=".$access_token;
$opts = array(
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 60,
CURLOPT_USERAGENT => 'facebook-php-3.1',
CURLOPT_CAINFO => /lib/fb_ca_chain_bundle.crt',
//replace the above path with proper path of the crt file
//in order to avoid the exceptions rendered by FB
//when we try to use CURL without proper certification file.
);
$opts[CURLOPT_URL] = $request_url;
if (isset($opts[CURLOPT_HTTPHEADER])) {
$existing_headers = $opts[CURLOPT_HTTPHEADER];
$existing_headers[] = 'Expect:';
$opts[CURLOPT_HTTPHEADER] = $existing_headers;
} else {
$opts[CURLOPT_HTTPHEADER] = array('Expect:');
}
$ch = curl_init();
curl_setopt_array($ch, $opts);
$result = curl_exec($ch);
if ($result === false) {
$e = new FacebookApiException(array(
'error_code' => curl_errno($ch),
'error' => array(
'message' => curl_error($ch),
'type' => 'CurlException',
),
));
curl_close($ch);
throw $e;
}
curl_close($ch);
$friends = json_decode(preg_replace('/"uid":(\d+)/','"uid":"$1"',$result));
I just to post this answers so it may help others until Facebook resolve this inconsistency.
There are two things very consistent about Facebook. They are: 1) changing their APIs at their whim without any headsup. 2) Inconsistency between graph and fql objects.
As you have indicated, the unquoted values returned from Facebook are always long's (aka big int, aka Int64). And the quoted values are string representations of the long value.
What it appears to me is that the $facebook->api call is munging the longs into floats. I'd suggest logging it as a bug with the $facebook->api team.
In the interim while they fix that bug, you can code your own code to do the HTTP post to the graph and parse the returned results. I don't encounter this issue with the C# API, nor with the Javascript API.
If youre using php (http://php.net/manual/en/function.sprintf.php):
printf("%14.0f", 1.00000145202E+14);
outputs:
100000145202000
Javascript:
parseFloat('1.00000145202E+14')