Twitter REST Api 1.1 POST friendships/create - twitter

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'));

Related

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.

tmhOauth twitter api stopped working with update_with_media call

So, this morning I got the following error:
{"errors": [{"message": "The Twitter REST API v1 will soon stop functioning.
Please migrate to API v1.1. https://dev.twitter.com/docs/api/1.1/overview.",
"code": 68}]}
Since I was using the tmhOauth twitter api I went to look if there are updates for it, and as it seems there is an issue listed here.
I'm using the api to update the status with media like this:
$code = $tmhOAuth->request('POST', 'https://upload.twitter.com/1/statuses/update_with_media.json',
array(
'media[]' => "#{$image}",
'status' => "{$text}"
),
true, // use auth
true // multipart
);
I found notes that I should just change the link to use 1.1 instead of 1 but it's still not working.
My main problem was that I didn't read the docs fully! While the change in the url from 1 to 1.1 was sufficient I missed the point by not looking that the new url for update_with_media,
as explained in the documentation, is https://api.twitter.com/1.1/statuses/update_with_media.json, namely it's api instead of the old upload subdomain.
So, now my api call looks like this and all works again:
$code = $tmhOAuth->request('POST', 'https://api.twitter.com/1.1/statuses/update_with_media.json',
array(
'media[]' => "#{$image}",
'status' => "{$text}"
),
true, // use auth
true // multipart
);
Hope this helps someone.
Instead of using tmhOauth api, use abraham's twitteroauth api ( updated to version 1.1 ) :
https://github.com/abraham/twitteroauth/tree/master/twitteroauth
and replace your code as follows :
$connection = new TwitterOAuth($twitter_consumer_key, $twitter_consumer_secret, $twAccessToken, $twAccessTokenSecret);
$parameters = array(
'media[]' => "#{$image}",
'status' => "{$text}"
);
$code = $connection->post('statuses/update_with_media', $parameters);

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

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.

"Could not authenticate you." -error when using Twitter OAuth

I'm building my first system using Twitters OAuth and have some issues.
First, I'm using Abraham's Twitter-class for this and I have followed this tutorial. However, I get these lines on my callback.php:
Warning: array_merge() [function.array-merge]: Argument #2 is not an array in C:\xampp\htdocs\twitter\twitterOAuth\OAuth.php on line 301
Warning: strtoupper() expects parameter 1 to be string, array given in C:\xampp\htdocs\twitter\twitterOAuth\OAuth.php on line 373
Oops - an error has occurred.
SimpleXMLElement Object
(
[request] => /account/verify_credentials.xml
[error] => Could not authenticate you.
)
Is this problem by Twitter-class, or am I doing something wrong? I have my Consumer Key and Consumer Secret in config.php as tutorial says, but should I store something else?
Martti Laine
The Snipe.net tutorial is for an older version of TwitterOAuth. Make sure you read the new documentation
http://github.com/abraham/twitteroauth/blob/master/DOCUMENTATION
In general updating to the new version is changing:
$content = $to->OAuthRequest('https://twitter.com/account/verify_credentials.xml', array(), 'GET');
to:
$content = $to->get('account/verify_credentials');
I was having the same error, caused by a simple mistake:
Doesn’t work:
$this->twitteroauth->post('statuses/update’, $message);
Works: $this->twitteroauth->post('statuses/update', array("status" => $message));

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