Setting up Twitter API, getting the last few Tweets
Asked Answered
T

3

27

I am completely new to using Twitter in general and have never embedded "latest tweets" on any project. I am simply trying to embed the 3-4 newest tweets on the site footer with no additional features of functionality. I have been researching how to do this for quite some time now and having some trouble.

I added the following code snippet to the project, which works quite well, however, I am not sure how to update the snippet so it uses my Twitter account instead of the one it is set up with.

    <div id="twitter_update_list">
    </div>
    <script type="text/javascript" src="http://api.twitter.com/1/statuses/user_timeline.json?screen_name=stackoverflow&include_rts=true&count=4&callback=twitterCallback2">
    </script>

In addition, I keep reading that the most commonly used Twitter API will stop working soon because Twitter wants people to use their own, as opposed to third party.

I am not sure how to proceed from here. I would greatly appreciate any suggestions in this regard. To recap, all I am trying to do is grab the 3-4 latest tweets from my account.

many thanks in advance!

Triage answered 11/6, 2013 at 17:5 Comment(1)
If you need a javascript-only solution, you can use the Twitter-Post-Fetcher of Jason Mayes jasonmayes.com/projects/twitterApi In a few days I'll try it for a new job, today it seems to be a good way for who can't work in the server side.Rosaleerosaleen
M
63

So you REALLY don't want to do this client-side anymore. (Just went through numerous docs, and devs suggest to do all oAuth server-side)

What you need to do:

First: sign up on https://dev.twitter.com, and make a new application.

Second: NOTE: Your Consumer Key / Secret along with Access Token / Secret

Third: Download Twitter OAuth Library (In this case I used the PHP Library https://github.com/abraham/twitteroauth , additional libraries located here: https://dev.twitter.com/docs/twitter-libraries)

Fourth: (If using PHP) Make sure cURL is enabled if your running on a LAMP here's the command you need:

sudo apt-get install php5-curl

Fifth: Make a new PHP file and insert the following: Thanks to Tom Elliot http://www.webdevdoor.com/php/authenticating-twitter-feed-timeline-oauth/

<?php
session_start();
require_once("twitteroauth/twitteroauth/twitteroauth.php"); //Path to twitteroauth library you downloaded in step 3

$twitteruser = "twitterusername"; //user name you want to reference
$notweets = 30; //how many tweets you want to retrieve
$consumerkey = "12345"; //Noted keys from step 2
$consumersecret = "123456789"; //Noted keys from step 2
$accesstoken = "123456789"; //Noted keys from step 2
$accesstokensecret = "12345"; //Noted keys from step 2

function getConnectionWithAccessToken($cons_key, $cons_secret, $oauth_token, $oauth_token_secret) {
  $connection = new TwitterOAuth($cons_key, $cons_secret, $oauth_token, $oauth_token_secret);
  return $connection;
}

$connection = getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);

$tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser."&count=".$notweets);

echo json_encode($tweets);
echo $tweets; //testing remove for production   
?>

And boom, you're done. I know this isn't a pure js solution but again reading through the new Twitter API 1.1 docs they REALLY don't want you to do this client-side. Hope this helps!

Mesdames answered 12/6, 2013 at 4:29 Comment(5)
Thanks for the reply! Thats a lot more work than expected to get 3 tweets, but I got to do what I got to do ;) I'll give this a try and check back.Triage
When you say "sign up on dev.twitter.com" - do you need to do that as the account you want to get the tweets from (my customer's acc) or just any account (ie my own account)?Purely
@Purely no it just has to be a twitter account. It's explained in the link in the fifth step aboveInquire
Would love to know the reason why devs suggest this should be done server side?Unobtrusive
@Seano because the tokens and keys are sensitive information that can give unauthorized access to Twitter if stolen, and they would be fully visible in Javascript code if done client side.Unsparing
C
25

How to get last few tweets of user with core PHP functionality only (no CURL or Twitter oAuth library needed):

  1. Register your app/webpage https://apps.twitter.com (You may need to verify your personal account mobile number too)

  2. Note Consumer Key and Consumer Secret

  3. PHP Code:

    // auth parameters
    $api_key = urlencode('REPLACEWITHAPPAPIKEY'); // Consumer Key (API Key)
    $api_secret = urlencode('REPLACEWITHAPPAPISECRET'); // Consumer Secret (API Secret)
    $auth_url = 'https://api.twitter.com/oauth2/token'; 
    
    // what we want?
    $data_username = 'Independent'; // username
    $data_count = 10; // number of tweets
    $data_url = 'https://api.twitter.com/1.1/statuses/user_timeline.json?tweet_mode=extended';
    
    // get api access token
    $api_credentials = base64_encode($api_key.':'.$api_secret);
    
    $auth_headers = 'Authorization: Basic '.$api_credentials."\r\n".
                    'Content-Type: application/x-www-form-urlencoded;charset=UTF-8'."\r\n";
    
    $auth_context = stream_context_create(
        array(
            'http' => array(
                'header' => $auth_headers,
                'method' => 'POST',
                'content'=> http_build_query(array('grant_type' => 'client_credentials', )),
            )
        )
    );
    
    $auth_response = json_decode(file_get_contents($auth_url, 0, $auth_context), true);
    $auth_token = $auth_response['access_token'];
    
    // get tweets
    $data_context = stream_context_create( array( 'http' => array( 'header' => 'Authorization: Bearer '.$auth_token."\r\n", ) ) );
    
    $data = json_decode(file_get_contents($data_url.'&count='.$data_count.'&screen_name='.urlencode($data_username), 0, $data_context), true);
    
    // result - do what you want
    print('<pre>');
    print_r($data);
    

Tested with XAMPP for Windows and Centos6 default installation (PHP 5.3)

Most probable problem with this might be that openssl is not enabled in php.ini

To fix check if extension=php_openssl.dll or extension=php_openssl.so line is present and uncommented in php.ini

Capet answered 9/3, 2015 at 17:53 Comment(5)
Thanks @Rauli! Would upvote more if I could :) Note to others: currently, twitter access tokens don't expire: #8358068, dev.twitter.com/oauth/overview/faqPrudence
Thanks for the answer, works very fine without download any library... Do you have any idea where I can find more documentation about this way to get data from twitter for retrive results coming from a hashtag? ThanksLubric
@FernandoUrban There is Twitter search API developer.twitter.com/en/docs/tweets/search/api-reference/… It has different data url and different parameters than my example, but otherwise it should work similarly.Capet
This still works great. All the available parameters can be found here: developer.twitter.com/en/docs/tweets/timelines/api-reference/…Fortnightly
Really old, but is there a way to modify this for twitter api v2?Sports
G
-16

Actually twitter has many restrictions, as there is lot of contest from companies like Nike and others. The reading of tweet is limited in the sense that if you are reading through the latest API its actually a bit behind time.

They have also controlled the DM delay which means you cannot DM instantly even if you do, the other party will only receive after X amount of time. If you do through script, and even if you try to DM a lot from one single ip twitter will simply BLOCK you.

Geriatric answered 5/9, 2013 at 10:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.