98

Is there a way in the Twitter API to get the replies to a particular tweet? Thanks

2

13 Answers 13

57

Here is the procedure to get the replies for a tweets

  1. when you fetch the tweet store the tweetId ie., id_str
  2. using twitter search api do the following query [q="to:$tweeterusername", sinceId = $tweetId]
  3. Loop all the results , the results matching the in_reply_to_status_id_str to $tweetid is the replies for the post.
0
54

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><a href="http://www.tweetdeck.com/">TweetDeck</a></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.

7
  • Lets say user2 replies to user1's tweet. To figure that out from user1's tweet, I would need to search for mentions for user1. But what in the case when I can't authenticate as user1 ? Aren't mentions accessible publicly without auth ?
    – letronje
    Commented Nov 14, 2010 at 15:13
  • @letronje Not that I know of - you could use the search API to find '@user1' in the tweet, but I don't think would be as reliable as using status/mentions.
    – Tim Lytle
    Commented Nov 14, 2010 at 21:06
  • 1
    Looks like statues/mentions is deprecated, so I'd parse search/tweets?q=@screenName instead: dev.twitter.com/docs/api/1.1/get/search/tweets
    – Dunc
    Commented Aug 13, 2014 at 9:38
  • 4
    @Dunc Looks like it's just been changed to status/mentions_timeline
    – Tim Lytle
    Commented Aug 13, 2014 at 23:09
  • @Tim Good point. But my use case is similar to letronje's (i.e. tweet could be from anyone) so I need to use search instead.
    – Dunc
    Commented Aug 14, 2014 at 10:39
19

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.

2
  • 2
    This will work, BUT the search/recent endpoint only returns results from the last 7 days. The search/all endpoint is restricted to apps with Academic Research access. Search documentation Commented Oct 15, 2022 at 19:36
  • is it possible to get the top replies using this method? instead of recent replies? Commented Oct 21, 2022 at 11:45
10

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

2
  • 38
    This API is not active anymore
    – mathieu
    Commented Oct 30, 2013 at 8:26
  • Yes. as mathieu said, it is no more active. It says {u'message': u'Sorry, that page does not exist', u'code': 34} Commented Mar 2, 2015 at 12:42
9

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;
     }

}
2
  • 3
    Why was this voted down? It works exactly as stated and answers the problem precisely. Furthermore, my method differs from @vsubbotin in that you can use any Tweeter's id instead of your own. Commented Aug 14, 2014 at 7:29
  • 4
    This is good, but can eat up valuable rate limits (180 per oauth). 180 tweets run with this method...see ya! Commented Feb 27, 2016 at 18:47
8

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.
5

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

2
  • is there a way to do this in javascript?
    – yashatreya
    Commented Apr 30, 2020 at 15:12
  • I am not sure, I didn't check, will let you know if found something. Commented May 1, 2020 at 17:09
3

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.

1
  • gnip.com is basically the only third-party place to get Twitter data now.
    – abraham
    Commented May 6, 2016 at 16:14
3

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

2

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;
2

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
                        )
                )
             ....             
        )
)
0
1

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.

0

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.