How do I format a retweet request through the Abraham twitteroauth php class? - twitter

I'm damned if I can make this work. Your help would be appreciated. I have valid access tokens, and can use twitteroauth to post status updates. However: every way I've tried to come at retweets has failed.
$parameters = array('id' => $status_id);
$retweet = $connection->post('statuses/retweet', $parameters);
Gets an error response of "not found." I'm not sure what's not found - the id of the tweet that I'm trying to retweet, or the method I'm calling (statuses/retweet). I'm passing valid ID's through the request (I can find them on Twitter), and so on. Any ideas?
Here's the documentation:
http://dev.twitter.com/doc/post/statuses/retweet/:id
I've also tried:
$parameters = array('id' => $status_id);
$retweet = $connection->post('statuses/retweet/', $parameters);
$parameters = array('id' => $status_id);
$retweet = $connection->post('statuses/retweet/:', $parameters);
and...
$retweet = $connection->post('statuses/retweet/:123456.json');
With either null responses (??) or the same enigmatic "not found."

$retweet = $connection->post('statuses/retweet/123456');
:id is a variable syntax that similar to PHP's $id so you replace it in its entirety with the value.
$parameters is only used when the key value pairs are getting added as URL parameters like ?key=value not in the URL path.
The format is automatically handled by the library so you should not include .json manually.

Another tip on this issue is to reference "id_str" rather than the "id" as the "id" integer is sometimes wrong.

Related

Twilio PHP SDK - Did twilio receive my request?

We are using the Twilio PHP SDK and the Notify Client. When I make a request how do I get the status of that request. Did it return a good 2XX, an error 4XX? And to be clear, I don't mean, what is the status of the messages. I simply mean, did twilio get my API call?
When testing in Postman with the REST API I typically get a 200 or 201 response if everything went well.
$twilio = new Client($acct_sid, $token);
$Addresses = array("+12015551234");
$toBindingAttributes = array();
foreach ($Addresses as $Address) {
array_push($toBindingAttributes, '{"binding_type":"sms","address":"' . $Address . '"}');
}
$notification = $twilio->notify->services($notify_sid)
->notifications->create([
"toBinding" => $toBindingAttributes,
"body" => "Twilio Test."
]);
I've tried to return $notification and I just get [Twilio.Notify.V1.NotificationInstance]
-----Edit-----
ok I realize now that [Twilio.Notify.V1.NotificationInstance] is an object. I was able to print_r($notification) and see that there is a statusCode property.
I tried to echo that property print_r(#notification->statusCode) but I get "Unknown Property".
Is it because it's "protected"?
[statusCode:protected] => 201
Thanks
Since the result is the [Twilio.Notify.V1.NotificationInstance] object.
The problem is all the properties within the object are protected we cannot access them directly.
We were able to get to them with a bunch of strpos, substr, and regex but found a much easier way using a getter.
By doing this way
print($twilio->getHttpClient()->lastResponse->getStatusCode());
More info in the Twilio-PHP library
https://github.com/twilio/twilio-php/blob/650f42647c9b3039e03ae075785164ec97203e94/src/Twilio/Http/Response.php

Drupal 8 Guzzle Format Query String

Forgive me for my ignorance, this is my first attempt at Drupal 8 and I'm not a good php developer to begin with. But I've been reading and searching for hours. I'm trying to do a post using the new Guzzle that replaces the drupal_http_request(). I've done this using Curl but can't seem to get this going in the right direction here. I'm just not "getting it".
Here is a sample of the array I have that pulls data from a custom form. I also tried this with a custom variable where I built the string.
$fields = array(
"enroll_id" => $plan,
"notice_date" => $date,
"effective_date" => $date,
);
$client = \Drupal::httpClient();
$response = $client->post('myCustomURL', ['query' => $fields]);
$data = $response->getBody()->getContents();
try {
drupal_set_message($data);
} catch (RequestException $e) {
watchdog_exception('MyCustomForm', $e->getMessage());
}
This indeed returns the result of REJECTED from my API in $data below - but it doesn't append the URL to included the query => array. I've tried numerous combinations of this just putting the fully built URL in the post (that works with my API - tested) and I still receive the same result from my API. In the end what I'm trying to accomplish is
https://myCustomURL?enroll_id=value&notice_date=12/12/12&effective_date=12/12/12
Any direction or tips would be much appreciated.
Thanks for the responses guys. I was able to get it to work correctly by changing a few things in my post. First changing client -> post to a request('POST', XXX) and then changing "query" to "form_params" as "body" has been deprecated.
http://docs.guzzlephp.org/en/latest/quickstart.html#query-string-parameters
$client = \Drupal::httpClient();
$response = $client->request('POST','https://myURL.html', ['form_params' => $fields]);
$data = $response->getBody()->getContents();
Using $client->post will send a POST request. By looking at the URL that you tested directly you want a GET request.
Either use $client->get or $client->request with the GET parameter. More information and examples in the Guzzle documentation.

Twitter REST Api 1.1 POST friendships/create

I was trying to implement Twitter friendships/create by using REST Api 1.1 with PHP. But no matter how I tried it returns with
stdClass Object
(
[errors] => Array
(
[0] => stdClass Object
(
[message] => Bad Authentication data
[code] => 215
)
)
)
and my code is (using Abraham library and changed twitterauth to v1.1)
$twitteroauth = new TwitterOAuth( $this->consumer_key, $this->consumer_secret, $oauth_token, $oauth_token_secret);
$test_create = $twitteroauth->post('friendships/create',array('follow'=>true,'user_id'=>'2529416xx'));
print_r($test_create);exit;
I'm not an expert (I've got the same problem), but I think you shouldn't change the oauth version since it remains 1.0a. More information can be found here https://dev.twitter.com/docs/api/1.1/overview#Authentication_required_on_all_endpoints and here https://dev.twitter.com/docs/auth/authorizing-request
The change it's only in the URL of the request, for instance:
https://api.twitter.com/1.1/statuses/mentions_timeline.json
I was having the same problem like yours also. And the solutions are simple : dont change the version number (remains 1.0) and change the host to $host = "https://api.twitter.com/1.1/";
that solved mine!
You can try this code
Here your_screen_name you need to pass your screen_name and instead of your_user_id you need to pass your user id
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['token'] , $_SESSION['token_secret']);
$connection->post('friendships/create', array('screen_name'=>'your_screen_name','user_id'=>'your_user_id','follow'=>'true'));

Google-api-client asking for access token

My requirement is to get top 20 links for a search query in google.com.
I am using the Google-api-client! for ruby.
Here goes the code I am using,
require 'google/api_client'
client = Google::APIClient.new
response = client.execute(
search.cse.list, 'key' => '<My Key>', 'cx' => '013036536707430787589%3A_pqjad5hr1a', 'alt' => 'json', 'q' => 'hello world'
)
Now I am facing three problems,
I want to use default Google search, so what should be the 'cx' value? One which I used, is from https://developers.google.com/custom-search/v1/using_rest#cx
I am getting no results, instead getting the following warning "ArgumentError: Missing access token." I solved this issue using a dummy token, by defining "client.authorization.access_token = '123'" . But I am not sure, if it is a correct solution or not.
After I define the access_token, still I am getting no result. Instead getting the warning "Invalid Credentials". But if I use the same URL(generated by the api), in the browser I am getting results.
Instead of setting a dummy access token, just set the authorization mechanism to nil:
client.authorization = nil
This way it won't send an authorization header and will just rely on the API key for identifying your app.

Replies to a particular tweet, Twitter API

Is there a way in the Twitter API to get the replies to a particular tweet? Thanks
Here is the procedure to get the replies for a tweets
when you fetch the tweet store the tweetId ie., id_str
using twitter search api do the following query
[q="to:$tweeterusername", sinceId = $tweetId]
Loop all the results , the results matching the in_reply_to_status_id_str to $tweetid is the replies for the post.
From what I understand, there's not a way to do that directly (at least not now). Seems like something that should be added. They recently added some 'retweet' capabilities, seem logical to add this as well.
Here's one possible way to do this, first sample tweet data (from status/show):
<status>
<created_at>Tue Apr 07 22:52:51 +0000 2009</created_at>
<id>1472669360</id>
<text>At least I can get your humor through tweets. RT #abdur: I don't mean this in a bad way, but genetically speaking your a cul-de-sac.</text>
<source>TweetDeck</source>
<truncated>false</truncated>
<in_reply_to_status_id></in_reply_to_status_id>
<in_reply_to_user_id></in_reply_to_user_id>
<favorited>false</favorited>
<in_reply_to_screen_name></in_reply_to_screen_name>
<user>
<id>1401881</id>
...
From status/show you can find the user's id. Then statuses/mentions_timeline will return a list of status for a user. Just parse that return looking for a in_reply_to_status_id matching the original tweet's id.
The Twitter API v2 supports this now using a conversation_id field. You can read more in the docs.
First, request the conversation_id field of the tweet.
https://api.twitter.com/2/tweets?ids=1225917697675886593&tweet.fields=conversation_id
Second, then search tweets using the conversation_id as the query.
https://api.twitter.com/2/tweets/search/recent?query=conversation_id:1225912275971657728
This is a minimal example, so you should add other fields as you need to the URL.
Twitter has an undocumented api called related_results. It will give you replies for the specified tweet id. Not sure how reliable it is as its experimental, however this is the same api call that is called on twitter web.
Use at your own risk. :)
https://api.twitter.com/1/related_results/show/172019363942117377.json?include_entities=1
For more info, check out this discussion on dev.twitter:
https://dev.twitter.com/discussions/293
Here is my solution. It utilizes Abraham's Twitter Oauth PHP library: https://github.com/abraham/twitteroauth
It requires you to know the Twitter user's screen_name attribute as well as the id_str attribute of the tweet in question. This way, you can get an arbitrary conversation feed from any arbitrary user's tweet:
*UPDATE: Refreshed code to reflect object access vs array access:
function get_conversation($id_str, $screen_name, $return_type = 'json', $count = 100, $result_type = 'mixed', $include_entities = true) {
$params = array(
'q' => 'to:' . $screen_name, // no need to urlencode this!
'count' => $count,
'result_type' => $result_type,
'include_entities' => $include_entities,
'since_id' => $id_str
);
$feed = $connection->get('search/tweets', $params);
$comments = array();
for ($index = 0; $index < count($feed->statuses); $index++) {
if ($feed->statuses[$index]->in_reply_to_status_id_str == $id_str) {
array_push($comments, $feed->statuses[$index]);
}
}
switch ($return_type) {
case 'array':
return $comments;
break;
case 'json':
default:
return json_encode($comments);
break;
}
}
Here I am sharing simple R code to fetch reply of specific tweet
userName = "SrBachchan"
##fetch tweets from #userName timeline
tweets = userTimeline(userName,n = 1)
## converting tweets list to DataFrame
tweets <- twListToDF(tweets)
## building queryString to fetch retweets
queryString = paste0("to:",userName)
## retrieving tweet ID for which reply is to be fetched
Id = tweets[1,"id"]
## fetching all the reply to userName
rply = searchTwitter(queryString, sinceID = Id)
rply = twListToDF(rply)
## eliminate all the reply other then reply to required tweet Id
rply = rply[!rply$replyToSID > Id,]
rply = rply[!rply$replyToSID < Id,]
rply = rply[complete.cases(rply[,"replyToSID"]),]
## now rply DataFrame contains all the required replies.
You can use twarc package in python to collect all the replies to a tweet.
twarc replies 824077910927691778 > replies.jsonl
Also, it is possible to collect all the reply chains (replies to the replies) to a tweet using command below:
twarc replies 824077910927691778 --recursive
Not in an easy pragmatic way. There is an feature request in for it:
http://code.google.com/p/twitter-api/issues/detail?id=142
There are a couple of third-party websites that provide APIs but they often miss statuses.
I've implemented this in the following way:
1) statuses/update returns id of the last status (if include_entities is true)
2) Then you can request statuses/mentions and filter the result by in_reply_to_status_id. The latter should be equal to the particular id from step 1
As states satheesh it works great. Here is REST API code what I used
ini_set('display_errors', 1);
require_once('TwitterAPIExchange.php');
/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
'oauth_access_token' => "xxxx",
'oauth_access_token_secret' => "xxxx",
'consumer_key' => "xxxx",
'consumer_secret' => "xxxx"
);
// Your specific requirements
$url = 'https://api.twitter.com/1.1/search/tweets.json';
$requestMethod = 'GET';
$getfield = '?q=to:screen_name&sinceId=twitter_id';
// Perform the request
$twitter = new TwitterAPIExchange($settings);
$b = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
$arr = json_decode($b,TRUE);
echo "Replies <pre>";
print_r($arr);
die;
I came across the same issue a few months ago at work, as I was previously using their related_tweets endpoint in REST V1.
So I had to create a workaround, which I have documented here:
http://adriancrepaz.com/twitter_conversations_api Mirror - Github fork
This class should do exactly what you want.
It scrapes the HTML of the mobile site, and parses a conversation. I've used it for a while and it seems very reliable.
To fetch a conversation...
Request
<?php
require_once 'acTwitterConversation.php';
$twitter = new acTwitterConversation;
$conversation = $twitter->fetchConversion(324215761998594048);
print_r($conversation);
?>
Response
Array
(
[error] => false
[tweets] => Array
(
[0] => Array
(
[id] => 324214451756728320
[state] => before
[username] => facebook
[name] => Facebook
[content] => Facebook for iOS v6.0 ? Now with chat heads and stickers in private messages, and a more beautiful News Feed on iPad itunes.apple.com/us/app/faceboo?
[date] => 16 Apr
[images] => Array
(
[thumbnail] => https://pbs.twimg.com/profile_images/3513354941/24aaffa670e634a7da9a087bfa83abe6_normal.png
[large] => https://pbs.twimg.com/profile_images/3513354941/24aaffa670e634a7da9a087bfa83abe6.png
)
)
[1] => Array
(
[id] => 324214861728989184
[state] => before
[username] => michaelschultz
[name] => Michael Schultz
[content] => #facebook good April Fools joke Facebook?.chat hasn?t changed. No new features.
[date] => 16 Apr
[images] => Array
(
[thumbnail] => https://pbs.twimg.com/profile_images/414193649073668096/dbIUerA8_normal.jpeg
[large] => https://pbs.twimg.com/profile_images/414193649073668096/dbIUerA8.jpeg
)
)
....
)
)
since statuses/mentions_timeline will return the 20 most recent mention this won't be that efficient to call, and it has limitations like 75 requests per window (15min) , insted of this we can use user_timeline
the best way: 1. get the screen_name or user_id parameters From status/show.
2. now use user_timeline
GET https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=screen_name&count=count
(screen_name== name which we got From status/show)
(count== 1 to max 200)
count: Specifies the number of Tweets to try and retrieve, up to a maximum of 200 per distinct request.
from the result Just parse that return looking for an in_reply_to_status_id matching the original tweet's id.
Obviously, it's not ideal, but it will work.
If you need all replies related to one user for ANY DATE RANGE, and you only need to do it once (like for downloading your stuff), it is doable.
Make a Twitter development application
Apply for elevated credentials. You will instantly get them after filling out the forms. At least I did on two separate accounts today.
Your development account now has access to the v1.1 API search in the "Sandbox" tier. You get 50 requests against the tweets/search/fullarchive endpoint maxing out at 5000 returned tweets.
Make an environment for your development application.
Make a script to query https://api.twitter.com/1.1/tweets/search/fullarchive/<env name>.json where <env name> is the name of your environment. Make your query to:your_twitter_username and fromDate when you created your account, toDate today.
Iterate over the results
This will not get your replies recursively

Resources