42

Which API would I need to use to get 'n' recent tweets of a particular user with a public account?

user330973
  • 823
  • 2
  • 9
  • 16
  • 2
    Which language are you using? – Tim Nov 11 '10 at 09:22
  • 1
    Here is a link where you'll find a code to select tweets using the twitter 1.1 API http://stackoverflow.com/questions/12916539/simplest-php-example-retrieving-user-timeline-with-twitter-api-version-1-1 – lackovic10 Dec 22 '12 at 23:24
  • 1
    If you ever come back online @user330973 - you should change the correct answer for this, for future proofness :) – Jimbo Jul 24 '13 at 10:05

5 Answers5

30

To get tweets from a specific user you will want to use the GET statuses/user_timeline API method.

MX D
  • 2,453
  • 4
  • 35
  • 47
abraham
  • 46,583
  • 10
  • 100
  • 152
13

As of May 7th, 2013, Twitter's already deprecated v1.0 is being retired and v1.1 is the only method of accessing the API, using authenticated requests via OAuth.

v1.0 deprecated

This means you won't be able to use PHP's file_get_contents() entirely on it's own to grab this sort of thing - you need to write a script that utilises OAuth and Twitters v1.1 API.

I recently wrote a Stack Overflow answer to help out newbies to the twitter v1.1 API, and I wrote a class to make this easier for you.

You need to create a developer account, grab yourself a set of developer keys to use within your application, and make authenticated requests using OAuth. If you read the post above, you'll see I created a simple class to allow you to do this.

TLDR: Can't use v1.0 any more, use 1.1 and this class for simplicity: https://github.com/J7mbo/twitter-api-php

Community
  • 1
  • 1
Jimbo
  • 25,790
  • 15
  • 86
  • 131
  • You *can* use file_get_contents with OAuth. – hakre Apr 29 '13 at 14:38
  • The shortcomming is also in your class on Github. Silly curl you bastard not needed if file_get_contents is there ;) (Fix first of all that error-message into something useful I'd say) – hakre Apr 29 '13 at 14:40
  • Lol! Hey, it does the job :P @hakre Show me what you suggest? – Jimbo Apr 29 '13 at 14:42
  • @Jimbo: Hi, I'm using `https://api.twitter.com/1/statuses/user_timeline.json?include_rts=true&screen_name=mehuljoisar&count=50` api to get public tweets from any user just by passing screen_name.will it work after retirement of api v1 as suggested on `https://dev.twitter.com/blog/api-v1-retirement-final-dates`? – Mehul Joisar May 04 '13 at 06:42
  • 1
    @MehulJoisar From now on you'll need to use authenticated requests, and also version 1.1 (not 1 like you're currently using). The docs for GET status/user_timeline show that oath is required. All 1.0 calls will stop working, so you'll need to use my class and register for some dev keys (see my post I linked above). Docs for statuses/user_timeline in 1.1: dev.twitter.com/docs/api/1.1/get/statuses/user_timeline – Jimbo May 07 '13 at 13:40
6

latest 5 tweets with PHP code.

$tweets_result=file_get_contents("https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=username&count=5");
$data=json_decode($tweets_result);
print_r($data);
NoNaMe
  • 6,020
  • 30
  • 82
  • 110
karambir
  • 101
  • 1
  • 1
1

We can use the twitter Rest api to get the tweets of particular user. You can download the source of Display Tweets of a particular user in an Android

activity_main.xml

<RelativeLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:id="@+id/rl_menu"
        android:background="@color/colorPrimaryDark">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Twitter Tweets"
            android:textColor="#ffffff"
            android:textSize="15dp"
            android:layout_centerInParent="true"/>
    </RelativeLayout>

    <ListView
        android:layout_width="match_parent"
        android:id="@+id/lv_list"
        android:layout_height="match_parent"
        android:layout_below="@+id/rl_menu"></ListView>

    </RelativeLayout>

MainActivity.java

package com.gettweets;

import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;

/**
 * Demonstrates how to use a twitter application keys to access a user's timeline
 */
public class MainActivity extends Activity {

    final static String ScreenName = "Deepshikhapuri";
    final static String LOG_TAG = "rnc";
    ListView lv_list;
    ArrayList<String> al_text = new ArrayList<>();
    Adapter obj_adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv_list = (ListView)findViewById(R.id.lv_list);

        downloadTweets();
    }

    // download twitter timeline after first checking to see if there is a network connection
    public void downloadTweets() {
        ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

        if (networkInfo != null && networkInfo.isConnected()) {
            new DownloadTwitterTask().execute(ScreenName);
        } else {
            Toast.makeText(getApplicationContext(),"Please check your internet connection",Toast.LENGTH_SHORT).show();
        }
    }

    // Uses an AsyncTask to download a Twitter user's timeline
    private class DownloadTwitterTask extends AsyncTask<String, Void, String> {
        final static String CONSUMER_KEY = "nW88XLuFSI9DEfHOX2tpleHbR";
        final static String CONSUMER_SECRET = "hCg3QClZ1iLR13D3IeMvebESKmakIelp4vwFUICuj6HAfNNCer";
        final static String TwitterTokenURL = "https://api.twitter.com/oauth2/token";
        final static String TwitterStreamURL = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=";
        final ProgressDialog dialog = new ProgressDialog(MainActivity.this);

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog.setTitle("Loading");
            dialog.setMessage("Please wait");
            dialog.show();

        }

        @Override
        protected String doInBackground(String... screenNames) {
            String result = null;

            if (screenNames.length > 0) {
                result = getTwitterStream(screenNames[0]);
            }
            return result;
        }

        // onPostExecute convert the JSON results into a Twitter object (which is an Array list of tweets
        @Override
        protected void onPostExecute(String result) {
            Log.e("result",result);
            dialog.dismiss();

            try {
                JSONArray jsonArray_data = new JSONArray(result);
                al_text.clear();
                for (int i=0; i<jsonArray_data.length();i++){

                    JSONObject jsonObject = jsonArray_data.getJSONObject(i);
                    al_text.add(jsonObject.getString("text"));

                }
            }catch (Exception e){
                e.printStackTrace();
            }



            // send the tweets to the adapter for rendering
            obj_adapter= new Adapter(getApplicationContext(), al_text);
            lv_list.setAdapter(obj_adapter);
        }


        // convert a JSON authentication object into an Authenticated object
        private Authenticated jsonToAuthenticated(String rawAuthorization) {
            Authenticated auth = null;
            if (rawAuthorization != null && rawAuthorization.length() > 0) {
                try {
                    Gson gson = new Gson();
                    auth = gson.fromJson(rawAuthorization, Authenticated.class);
                } catch (IllegalStateException ex) {
                    // just eat the exception
                }
            }
            return auth;
        }

        private String getResponseBody(HttpRequestBase request) {
            StringBuilder sb = new StringBuilder();
            try {

                DefaultHttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
                HttpResponse response = httpClient.execute(request);
                int statusCode = response.getStatusLine().getStatusCode();
                String reason = response.getStatusLine().getReasonPhrase();

                if (statusCode == 200) {

                    HttpEntity entity = response.getEntity();
                    InputStream inputStream = entity.getContent();

                    BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                    String line = null;
                    while ((line = bReader.readLine()) != null) {
                        sb.append(line);
                    }
                } else {
                    sb.append(reason);
                }
            } catch (UnsupportedEncodingException ex) {
            } catch (ClientProtocolException ex1) {
            } catch (IOException ex2) {
            }
            return sb.toString();
        }

        private String getTwitterStream(String screenName) {
            String results = null;

            // Step 1: Encode consumer key and secret
            try {
                // URL encode the consumer key and secret
                String urlApiKey = URLEncoder.encode(CONSUMER_KEY, "UTF-8");
                String urlApiSecret = URLEncoder.encode(CONSUMER_SECRET, "UTF-8");

                // Concatenate the encoded consumer key, a colon character, and the
                // encoded consumer secret
                String combined = urlApiKey + ":" + urlApiSecret;

                // Base64 encode the string
                String base64Encoded = Base64.encodeToString(combined.getBytes(), Base64.NO_WRAP);

                // Step 2: Obtain a bearer token
                HttpPost httpPost = new HttpPost(TwitterTokenURL);
                httpPost.setHeader("Authorization", "Basic " + base64Encoded);
                httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
                httpPost.setEntity(new StringEntity("grant_type=client_credentials"));
                String rawAuthorization = getResponseBody(httpPost);
                Authenticated auth = jsonToAuthenticated(rawAuthorization);

                // Applications should verify that the value associated with the
                // token_type key of the returned object is bearer
                if (auth != null && auth.token_type.equals("bearer")) {

                    // Step 3: Authenticate API requests with bearer token
                    HttpGet httpGet = new HttpGet(TwitterStreamURL + screenName);

                    // construct a normal HTTPS request and include an Authorization
                    // header with the value of Bearer <>
                    httpGet.setHeader("Authorization", "Bearer " + auth.access_token);
                    httpGet.setHeader("Content-Type", "application/json");
                    // update the results with the body of the response
                    results = getResponseBody(httpGet);
                }
            } catch (UnsupportedEncodingException ex) {
            } catch (IllegalStateException ex1) {
            }
            return results;
        }
    }
}

Authenticated.java package com.gettweets;

public class Authenticated {
    String token_type;
    String access_token;
}

adapter_layout.xml

<RelativeLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv_text"
        android:textSize="18dp"
        android:layout_margin="10dp"
        android:textColor="#000000"/>

    </RelativeLayout>

Adapter.java

package com.gettweets;

import android.content.Context;
import android.graphics.Typeface;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;



public class Adapter extends ArrayAdapter<String> {

    Context context;
    ViewHolder viewHolder;
    ArrayList<String> al_newslist=new ArrayList<>();

    public Adapter(Context context,   ArrayList<String> al_newslist) {
        super(context, R.layout.adapter_layout, al_newslist);
        this.al_newslist=al_newslist;
        this.context=context;



    }

    @Override
    public int getCount() {

        Log.e("ADAPTER LIST SIZE",al_newslist.size()+"");
        return al_newslist.size();
    }
    @Override
    public int getItemViewType(int position) {
        return position;
    }

    @Override
    public int getViewTypeCount() {
        if (al_newslist.size() > 0) {
            return al_newslist.size();
        } else {
            return 1;
        }
    }
    @Override
    public long getItemId(int position) {
        return position;
    }



    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        if (convertView == null) {

            viewHolder = new ViewHolder();
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.adapter_layout, parent, false);
            viewHolder.tv_name = (TextView) convertView.findViewById(R.id.tv_text);



            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }


       viewHolder.tv_name.setText(al_newslist.get(position));


        return convertView;

    }

    private static class ViewHolder {
        TextView tv_name;



    }

}
Deepshikha Puri
  • 2,104
  • 22
  • 23
0

To get the tweets of a specific Twitter account you can use the new User Tweet Timeline API methods added in Twitter API v2.

seebham
  • 41
  • 3
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 20 '21 at 11:20