Showing posts with label twitter. Show all posts
Showing posts with label twitter. Show all posts

Sunday, March 27, 2011

How to retrieve your twitter feeds in PERL

Retrieving twitter feeds is very simple and easy, you only need an HTTP request that returns format such as JSON, XML, RSS, and ATOM. This method doesn't require authentication.

Just follow the simple steps below using PERL. Hope you like it!

1. Install LWP::UserAgent in your server.

2. Initialize libraries, header and user agent.

require LWP::UserAgent;

my $lwpua = LWP::UserAgent->new;

my $uagent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ('Referer' => 'http://api.twitter.com/',
             'User-Agent' => $uagent);

3. Compose the HTTP request.

my $twuser = '<your twitter username>';
my $twurl = "http://api.twitter.com/1/statuses/user_timeline.<format>?screen_name=$twuser";

Supported Format:
  • JSON
  • XML
  • RSS
  • ATOM
URL Parameters:
  • user_id - The id of twitter account you want to retrieve.
  • screen_name - The username of twitter account you want to retrieve.
  • since_id - This will return the feeds after or more than the specified message id.
  • max_id - This will return the feeds before or less than the specified message id.
  • count - The number of tweets to be retrieve.
  • page - This will specify the page of the result to retrieve.
  • trim_user - When set to either true, t or 1, each tweet returned in a timeline will include a user object including only the status authors numerical id.
  • include_rts - When set to either true, t or 1, the timeline will contain native retweets (if they exist) in addition to the standard stream of tweets.
  • include_entities - When set to either true, t or 1, each tweet will include a node called "entities". This node offers a variety of metadata about the tweet in a discreet structure, including: user_mentions, urls, and hashtags. While entities are opt-in on timelines at present, they will be made a default component of output in the future.
4. Execute HTTP GET request.

my $response = $lwpua->get($twurl, @header);
my $return = $response->content;


That's it!! Please see below for the complete code using JSON format.

#!/usr/bin/perl

require LWP::UserAgent;
use JSON;

my $lwpua = LWP::UserAgent->new;

my $uagent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ('Referer' => 'http://api.twitter.com/', 'User-Agent' => $uagent);

my $twuser = '<your twitter username>';
my $twurl = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name=$twuser";

my $response = $lwpua->get($twurl, @header);
my $return = $response->content;

my $json = JSON->new->allow_nonref;
my $json_text = $json->decode($return);

my @tweets = @{$json_text};

my $message;
foreach $tweet (@tweets)
{
  $message .= $tweet->{text}."\n";
}

print "$message";



1;

Resource: dev.twitter.com

Tuesday, February 15, 2011

How to post tweet using OAuth access Token in PERL

OAuth access Token was gain from my previous post - How to exchange requested Token for an access Token from Twitter in PERL

In posting a tweet, we will use the resource URL - http://api.twitter.com/1/statuses/update.json and the POST method.

Just follow the steps below to post tweet on users behalf.

1. Install the following libraries.
  • LWP::UserAgent
  • HTTP::Cookies
  • Digest::MD5
  • Digest::SHA
  • POSIX

2. Initialize the libraries.

require LWP::UserAgent;

use HTTP::Cookies;

use Digest::MD5 qw(md5 md5_hex md5_base64);
use Digest::SHA qw(sha1 sha1_hex sha1_base64 hmac_sha1 hmac_sha1_hex hmac_sha1_base64);

use POSIX qw(strftime);

my $lwpua = LWP::UserAgent->new;

3. Setup the UserAgent and HTTP header with the name "Authorization" equal to "OAuth".

my $uagent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ('Referer' => 'https://api.twitter.com/',
             'User-Agent' => $uagent,
             'Authorization' => 'OAuth');

4. Build the signature base and signing key. Please take note that some parameters should be URL Encoded, see the post for the PERL function that you can use - URLENCODE sub function in PERL.

You need the consumer key and secret which was generated by Twitter upon registration.

You also need the Oauth Token and Secret which you get when exchanging the requested token for an access token.

To generate NONCE, we use Digest::MD5::md5_base64() passing the localtime(). We do it twice to make it much UNIQUE.

Timestamp was generated by using POSIX::strftime() with date format UNIXTIME as "%s".

Signing key was generated by combining the 2 parameters: Consumer Secret and OAuth Token Secret delimited by ampersand "&"

my $strToken = "<your oauth access token>";
my $strSecret = "<your oauth access token secret>";
my $strStatus = "<your tweet>";

my $post_url = "http://api.twitter.com/1/statuses/update.json";
my $nonce = md5_base64(localtime()).md5_base64(localtime());
my $timestamp = strftime('%s', localtime);
my $method = "HMAC-SHA1";
my $version = "1.0";
my $consumer_key = "<your consumer key generated upon registration>";
my $consumer_secret = "<your consumer secret generated upon registration>";

my $post_urlenc = &urlencode($post_url);
my $status_enc = &urlencode($strStatus);

my $oauth_data = "oauth_consumer_key=$consumer_key&oauth_nonce=$nonce&oauth_signature_method=$method&oauth_timestamp=$timestamp&oauth_token=$strToken&oauth_version=$version&status=$status_enc";
my $oauth_dataenc = &urlencode($oauth_data);

my $sign_base = "POST&".$post_urlenc."&".$oauth_dataenc;
my $sign_key = $consumer_secret."&".$strSecret;

5. Generate the OAuth Signature using HMAC-SHA1 method.

my $oauth_sign = hmac_sha1_base64($sign_base, $sign_key)."=";

6. Post an OAuth request with all the parameters you passed on step #4.

my $response = $lwpua->post($post_url,
                        ['oauth_token' => $strToken,
                         'oauth_consumer_key' => $consumer_key,
                         'oauth_nonce' => $nonce,
                         'oauth_signature_method' => $method,
                         'oauth_signature' => $oauth_sign,
                         'oauth_timestamp' => $timestamp,
                         'status' => $strStatus,
                         'oauth_version' => $version], @header);

print $response->content;

7. To know if successful, you can print the response and it should be look like this.

{
    "geo":null,
    "created_at":"Mon Apr 26 23:45:50 +0000 2010",
    "in_reply_to_user_id":null,
    "truncated":false,
    "place":null,
    "source":"&lt;a href=\"http://dev.twitter.com\" rel=\"nofollow\"&gt;OAuth Dancer&lt;/a&gt;",
    "favorited":false,
    "in_reply_to_status_id":null,
    "contributors":null,
    "user":
    {
        "contributors_enabled":false,
        "created_at":"Wed Mar 07 22:23:19 +0000 2007",
        "description":"Reality Technician,
         Developer Advocate at Twitter,
         Invader from the Space.",
        "geo_enabled":true,
        "notifications":false,
        "profile_text_color":"000000",
        "following":false,
        "time_zone":"Pacific Time (US &amp; Canada)",
        "verified":false,
        "profile_link_color":"731673",
        "url":"http://bit.ly/5w7P88",
        "profile_background_image_url":"http://a3.twimg.com/profile_background_images/19651315/fiberoptics.jpg",
        "profile_sidebar_fill_color":"007ffe",
        "location":"San Francisco,
         CA",
        "followers_count":1220,
        "profile_image_url":"http://a3.twimg.com/profile_images/836683953/zod_normal.jpg",
        "profile_background_tile":true,
        "profile_sidebar_border_color":"bb0e79",
        "protected":false,
        "friends_count":1275,
        "screen_name":"episod",
        "name":"Taylor Singletary",
        "statuses_count":5733,
        "id":819797,
        "lang":"en",
        "utc_offset":-28800,
        "favourites_count":89,
        "profile_background_color":"000000"
    },
    "in_reply_to_screen_name":null,
    "coordinates":null,
    "id":12912397434,
    "text":"setting up my twitter \u79c1\u306e\u3055\u3048\u305a\u308a\u3092\u8a2d\u5b9a\u3059\u308b"
}


Please see the complete code below.

#!/usr/bin/perl

require LWP::UserAgent;

use strict;
use warnings;

use HTTP::Cookies;

use Digest::MD5 qw(md5 md5_hex md5_base64);
use Digest::SHA qw(sha1 sha1_hex sha1_base64 hmac_sha1 hmac_sha1_hex hmac_sha1_base64);

use POSIX qw(strftime);


my $lwpua = LWP::UserAgent->new;

my $uagent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ('Referer' => 'https://api.twitter.com/',
             'User-Agent' => $uagent,
             'Authorization' => 'OAuth');

# build signature base
my $strToken = "<your oauth access token>";
my $strSecret = "<your oauth access token secret>";
my $strStatus = "<your tweet>";

my $post_url = "http://api.twitter.com/1/statuses/update.json";
my $nonce = md5_base64(localtime()).md5_base64(localtime());
my $timestamp = strftime('%s', localtime);
my $method = "HMAC-SHA1";
my $version = "1.0";
my $consumer_key = "<your consumer key generated upon registration>";
my $consumer_secret = "<your consumer secret generated upon registration>";

my $post_urlenc = &urlencode($post_url);
my $status_enc = &urlencode($strStatus);
my $oauth_data = "oauth_consumer_key=$consumer_key&oauth_nonce=$nonce&oauth_signature_method=$method&oauth_timestamp=$timestamp&oauth_token=$strToken&oauth_version=$version&status=$status_enc";
my $oauth_dataenc = &urlencode($oauth_data);

my $sign_base = "POST&".$post_urlenc."&".$oauth_dataenc;
my $sign_key = $consumer_secret."&".$strSecret;

# oauth signature
my $oauth_sign = hmac_sha1_base64($sign_base, $sign_key)."=";

# post oauth request
my $response = $lwpua->post($post_url,
                        ['oauth_token' => $strToken,
                         'oauth_consumer_key' => $consumer_key,
                         'oauth_nonce' => $nonce,
                         'oauth_signature_method' => $method,
                         'oauth_signature' => $oauth_sign,
                         'oauth_timestamp' => $timestamp,
                         'status' => $strStatus,
                         'oauth_version' => $version], @header);

print $response->content;



1;

Monday, February 14, 2011

How to exchange a requested TOKEN for an access TOKEN from Twitter in PERL

Finally, we're here at the last part of OAuth process, exchanging the requested token for an access token. I assume you were able to follow my last 2 posts below.
To get an access token, we need the OAuth Token, and Verifier from the previous post.

Just follow the simple steps below to gain an access token which we will use to access Twitter API in users behalf. This is likely the same when requesting a token, the only difference are the parameters we pass on.

1. Install all the libraries you need.
  • LWP::UserAgent
  • HTTP::Cookies
  • Digest::MD5
  • Digest::SHA
  • POSIX

2. Initialize the libraries

require LWP::UserAgent;

use strict;
use warnings;

use HTTP::Cookies;

use Digest::MD5 qw(md5 md5_hex md5_base64);
use Digest::SHA qw(sha1 sha1_hex sha1_base64 hmac_sha1 hmac_sha1_hex hmac_sha1_base64);

use POSIX qw(strftime);

my $lwpua = LWP::UserAgent->new;

3. Setup the UserAgent and HTTP header with the name "Authorization" equal to "OAuth".

my $uagent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ('Referer' => 'https://api.twitter.com/',
             'User-Agent' => $uagent,
             'Authorization' => 'OAuth');

4. Build the signature base and signing key. Please take note that some parameters should be URL Encoded, see the post for the PERL function that you can use - URLENCODE sub function in PERL.

You need the consumer key and secret which was generated by Twitter upon registration.

You also need the Oauth Token and Verifier which you get when authorizing the requested token.

To generate NONCE, we use Digest::MD5::md5_base64() passing the localtime(). We do it twice to make it much UNIQUE.

Timestamp was generated by using POSIX::strftime() with date format UNIXTIME as "%s".

# build signature base
my $strToken = "<your oauth token>";
my $strVerifier = "<your oauth verifier>";

my $post_url = "https://api.twitter.com/oauth/access_token";
my $nonce = md5_base64(localtime()).md5_base64(localtime());
my $timestamp = strftime('%s', localtime);
my $method = "HMAC-SHA1";
my $version = "1.0";
my $consumer_key = "<your consumer key generated upon registration>";
my $consumer_secret = "<your consumer secret generated upon registration>";

my $post_urlenc = &urlencode($post_url);

my $oauth_data = "oauth_consumer_key=$consumer_key&oauth_nonce=$nonce&oauth_signature_method=$method&oauth_timestamp=$timestamp&oauth_token=$strToken&oauth_verifier=$strVerifier&oauth_version=$version";
my $oauth_dataenc = &urlencode($oauth_data);

my $sign_base = "POST&".$post_urlenc."&".$oauth_dataenc;
my $sign_key = $consumer_secret."&";

5. Generate the OAuth Signature using HMAC-SHA1 method.

my $oauth_sign = hmac_sha1_base64($sign_base, $sign_key)."=";

6. Post an OAuth request with all the parameters you passed on step #4.

my $response = $lwpua->post($post_url,
                        ['oauth_token' => $strToken,
                         'oauth_verifier' => $strVerifier,
                         'oauth_consumer_key' => $consumer_key,
                         'oauth_nonce' => $nonce,
                         'oauth_signature_method' => $method,
                         'oauth_signature' => $oauth_sign,
                         'oauth_timestamp' => $timestamp,
                         'oauth_version' => $version], @header);
my $form_data = $response->content;

7. Get the return value: oauth_token, oauth_token_secret, user_id, and screen_name

$form_data =~ s/\n//g;
$form_data =~ /^oauth_token=(.*?)&oauth_token_secret=(.*?)&user_id=(.*?)&screen_name=(.*?)\s*$/gi;

my $oauth_token = $1;
my $oauth_secret = $2;
my $user_id = $3;
my $screen_name = $4;


Hope you like it! Please see the complete code below. Thank you for reading.

#!/usr/bin/perl

require LWP::UserAgent;

use strict;
use warnings;

use HTTP::Cookies;

use Digest::MD5 qw(md5 md5_hex md5_base64);
use Digest::SHA qw(sha1 sha1_hex sha1_base64 hmac_sha1 hmac_sha1_hex hmac_sha1_base64);

use POSIX qw(strftime);


my $lwpua = LWP::UserAgent->new;

my $uagent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ('Referer' => 'https://api.twitter.com/',
             'User-Agent' => $uagent,
             'Authorization' => 'OAuth');

# build signature base
my $strToken = "<your oauth token>";
my $strVerifier = "<your oauth verifier>";

my $post_url = "https://api.twitter.com/oauth/access_token";
my $nonce = md5_base64(localtime()).md5_base64(localtime());
my $timestamp = strftime('%s', localtime);
my $method = "HMAC-SHA1";
my $version = "1.0";
my $consumer_key = "<your consumer key generated upon registration>";
my $consumer_secret = "<your consumer secret generated upon registration>";

my $post_urlenc = &urlencode($post_url);
my $oauth_data = "oauth_consumer_key=$consumer_key&oauth_nonce=$nonce&oauth_signature_method=$method&oauth_timestamp=$timestamp&oauth_token=$strToken&oauth_verifier=$strVerifier&oauth_version=$version";
my $oauth_dataenc = &urlencode($oauth_data);

my $sign_base = "POST&".$post_urlenc."&".$oauth_dataenc;
my $sign_key = $consumer_secret."&";

  # oauth signature
my $oauth_sign = hmac_sha1_base64($sign_base, $sign_key)."=";

# post oauth request
my $response = $lwpua->post($post_url,
                        ['oauth_token' => $strToken,
                         'oauth_verifier' => $strVerifier,
                         'oauth_consumer_key' => $consumer_key,
                         'oauth_nonce' => $nonce,
                         'oauth_signature_method' => $method,
                         'oauth_signature' => $oauth_sign,
                         'oauth_timestamp' => $timestamp,
                         'oauth_version' => $version], @header);
my $form_data = $response->content;

$form_data =~ s/\n//g;
$form_data =~ /^oauth_token=(.*?)&oauth_token_secret=(.*?)&user_id=(.*?)&screen_name=(.*?)\s*$/gi;

my $oauth_token = $1;
my $oauth_secret = $2;
my $user_id = $3;
my $screen_name = $4;

print "$oauth_token|$oauth_secret|$user_id|$screen_name\n";
print "done!";


sub urlencode
{
  my ($url) = @_;

  $url =~ s/([^A-Za-z0-9_.-])/sprintf("%%%02X", ord($1))/seg;
  return $url;
}



1;

How to authorize OAuth TOKEN from Twitter in PERL

I assume you read my previous post - How to request OAuth TOKEN from Twitter in PERL before reading this post. You need the OAuth Token and Secret to proceed to this process.

On this post, we will login to twitter via back-end, please see post - Login to Twitter via backend using PERL on how to do it. Once the user had been logged in, we will authorize our application to post tweet and access users information in users behalf.

This post will outputted an OAuth Token and Verifier which you will use to Access Token "final oauth process" to get the OAuth Token and OAuth Secret.

Follow the simple steps below to authorize your application.

1. Install the following libraries.
  • LWP::UserAgent
  • HTTP::Cookies

2. Initialize the libraries.

require LWP::UserAgent;
use HTTP::Cookies;
my $lwpua = LWP::UserAgent->new;

3. Setup UserAgent, HTTP Header, and Cookies.

my $uagent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ('Referer' => 'https://api.twitter.com/',
             'User-Agent' => $uagent);

my $cookie_file = "/home/wapps/tweext/cookies/twitter/cookies.$intMsisdn.dat";
my $cookie_jar = HTTP::Cookies->new(
                file => $cookie_file,
                autosave => 1,
                ignore_discard => 1);

my $lwpua->cookie_jar($cookie_jar);

4. Post the OAuth Token with Username and Password to authorize URL - https://api.twitter.com/oauth/authorize

my $strToken = "<your oauth token>";
my $strUser = "<your twitter username>";
my $strPass = "<your twitter password>";

my $response = $lwpua->post("https://api.twitter.com/oauth/authorize",
                          ['oauth_token' => $strToken,
                           'session[username_or_email]' => $strUser,
                           'session[password]' => $strPass], @header);
my $cookie_jar->extract_cookies( $response );
my $cookie_jar->save;

$form_data = $response->content;

5. Get the OAuth Token and Oauth Verifier from the output returned by step #4.

$form_data =~ s/\n//g;
$form_data =~ /meta http-equiv="refresh" content="0;url=(.*?)\?oauth_token=(.*?)&oauth_verifier=(.*?)"/ig;

my $oauth_token = $2;
my $oauth_verif = $3;

unlink($cookie_file);



1;


Please see the complete code below. Thank you for reading this post.

#!/usr/bin/perl

require LWP::UserAgent;

use strict;
use warnings;

use HTTP::Cookies;

my $lwpua = LWP::UserAgent->new;

my $uagent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ('Referer' => 'https://api.twitter.com/',
             'User-Agent' => $uagent);

my $cookie_file = "/home/wapps/tweext/cookies/twitter/cookies.$intMsisdn.dat";
my $cookie_jar = HTTP::Cookies->new(
                file => $cookie_file,
                autosave => 1,
                ignore_discard => 1);

my $lwpua->cookie_jar($cookie_jar);

my $strToken = "<your oauth token>";
my $strUser = "<your twitter username>";
my $strPass = "<your twitter password>";

my $response = $lwpua->post("https://api.twitter.com/oauth/authorize",
                          ['oauth_token' => $strToken,
                           'session[username_or_email]' => $strUser,
                           'session[password]' => $strPass], @header);
my $cookie_jar->extract_cookies( $response );
my $cookie_jar->save;

$form_data = $response->content;

$form_data =~ s/\n//g;
$form_data =~ /meta http-equiv="refresh" content="0;url=(.*?)\?oauth_token=(.*?)&oauth_verifier=(.*?)"/ig;

my $oauth_token = $2;
my $oauth_verif = $3;

unlink($cookie_file);



1;

Sunday, February 13, 2011

How to request OAuth TOKEN from Twitter in PERL

For us to be able to request for a token, the first thing you have to do is to register your application.

To register an app, access the Client Applications page of Twitter. Registering your application allows twitter to identify your application. Remember not to reveal your consumer secrets with anyone.

While creating an application, you will be asked whether your application is a client or browser application, choose browser for this post.



Client applications need not to enter a callback URL. In fact, web applications need not to supply a callback URL either, but as best practice, you should submit your oauth_callback_url on every token request, explicitly declaring what you want the callback to be. This will also be needed to identify the variables we need since we're doing it backend.

You will also be asked for an access type, choose "read and write" for you to be able to post tweet eventually.



After registering your application, you will have the 2 important details below.
  • Consumer Key
  • Consumer Secret
Once you have those details, we are now ready to do the coding part. Just follow the simple steps below and you will be able to retrieve a token from Twitter.

Please take note that this token is not yet ready to access twitter on users behalf. The returned token by this process will be use to AUTHORIZE "next to this oauth process" and ACCESS TOKEN "final oauth process".

1. Install the libraries you need.
  • LWP::UserAgent
  • HTTP::Cookies
  • Digest::MD5
  • Digest::SHA
  • POSIX

2. Initialize the following libraries.

require LWP::UserAgent;

use HTTP::Cookies;

use Digest::MD5 qw(md5 md5_hex md5_base64);
use Digest::SHA qw(sha1 sha1_hex sha1_base64 hmac_sha1 hmac_sha1_hex hmac_sha1_base64);

use POSIX qw(strftime);

my $lwpua = LWP::UserAgent->new;

3. Setup the UserAgent and HTTP header with the name "Authorization" equal to "OAuth".

my $uagent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ('Referer' => 'https://api.twitter.com/',
             'User-Agent' => $uagent,
             'Authorization' => 'OAuth');

4. Build the signature base and signing key. Please take note that some parameters should be URL Encoded, see the post for the PERL function that you can use - URLENCODE sub function in PERL.

You need the callback URL which you define during client registration, and the consumer key and secret which was generated by Twitter upon registration.

To generate NONCE, we use Digest::MD5::md5_base64() passing the localtime(). We do it twice to make it much UNIQUE.

Timestamp was generated by using POSIX::strftime() with date format UNIXTIME as "%s".

my $post_url = "https://api.twitter.com/oauth/request_token";
my $callback_url = "<your callback url define on client registration>";
my $nonce = md5_base64(localtime()).md5_base64(localtime());
my $timestamp = strftime('%s', localtime);
my $method = "HMAC-SHA1";
my $version = "1.0";
my $consumer_key = "<your consumer key generated upon registration>";
my $consumer_secret = "<your consumer secret generated upon registration>";

my $callback_urlenc = &urlencode($callback_url);
my $post_urlenc = &urlencode($post_url);

my $oauth_data = "oauth_callback=$callback_urlenc&oauth_consumer_key=$consumer_key&oauth_nonce=$nonce&oauth_signature_method=$method&oauth_timestamp=$timestamp&oauth_version=$version";
my $oauth_dataenc = &urlencode($oauth_data);

my $sign_base = "POST&".$post_urlenc."&".$oauth_dataenc;
my $sign_key = $consumer_secret."&";

5. Generate the OAuth Signature using HMAC-SHA1 method.

my $oauth_sign = hmac_sha1_base64($sign_base, $sign_key)."=";

6. Post an OAuth request with all the parameters you passed on step #4.

my $response = $lwpua->post($post_url,
                        ['oauth_callback' => $callback_url,
                         'oauth_consumer_key' => $consumer_key,
                         'oauth_nonce' => $nonce,
                         'oauth_signature_method' => $method,
                         'oauth_signature' => $oauth_sign,
                         'oauth_timestamp' => $timestamp,
                         'oauth_version' => $version], @header);
my $form_data = $response->content;

7. Get the return value: oauth_token, oauth_token_secret, and oauth_callback_confirmed

$form_data =~ s/\n//g;
$form_data =~ /^oauth_token=(.*?)&oauth_token_secret=(.*?)&oauth_callback_confirmed=(.*?)\s*$/gi;

my $oauth_token = $1;
my $oauth_secret = $2;
my $oauth_confirm = $3;


Hope you like it!! Please see the complete code below.

#!/usr/bin/perl

require LWP::UserAgent;

use strict;
use warnings;

use HTTP::Cookies;

use Digest::MD5 qw(md5 md5_hex md5_base64);
use Digest::SHA qw(sha1 sha1_hex sha1_base64 hmac_sha1 hmac_sha1_hex hmac_sha1_base64);

use POSIX qw(strftime);

my $lwpua = LWP::UserAgent->new;

my $uagent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ('Referer' => 'https://api.twitter.com/',
             'User-Agent' => $uagent,
             'Authorization' => 'OAuth');

# build the signature base
my $post_url = "https://api.twitter.com/oauth/request_token";
my $callback_url = "http://flusso1.wolfpac.net/tweext/twitter.php";
my $nonce = md5_base64(localtime()).md5_base64(localtime());
my $timestamp = strftime('%s', localtime);
my $method = "HMAC-SHA1";
my $version = "1.0";
my $consumer_key = "fy13RaNud7FQl1AVafzq9g";
my $consumer_secret = "3FHgsf5ychPlLPaDF7f1RRjJthU5rPMCPa9kpJbbpK4";

my $callback_urlenc = &urlencode($callback_url);
my $post_urlenc = &urlencode($post_url);

my $oauth_data = "oauth_callback=$callback_urlenc&oauth_consumer_key=$consumer_key&oauth_nonce=$nonce&oauth_signature_method=$method&oauth_timestamp=$timestamp&oauth_version=$version";
my $oauth_dataenc = &urlencode($oauth_data);

my $sign_base = "POST&".$post_urlenc."&".$oauth_dataenc;
my $sign_key = $consumer_secret."&";

# oauth signature
my $oauth_sign = hmac_sha1_base64($sign_base, $sign_key)."=";

# post oauth request
my $response = $lwpua->post($post_url,
                        ['oauth_callback' => $callback_url,
                         'oauth_consumer_key' => $consumer_key,
                         'oauth_nonce' => $nonce,
                         'oauth_signature_method' => $method,
                         'oauth_signature' => $oauth_sign,
                         'oauth_timestamp' => $timestamp,
                         'oauth_version' => $version], @header);
my $form_data = $response->content;

$form_data =~ s/\n//g;
$form_data =~ /^oauth_token=(.*?)&oauth_token_secret=(.*?)&oauth_callback_confirmed=(.*?)\s*$/gi;

my $oauth_token = $1;
my $oauth_secret = $2;
my $oauth_confirm = $3;

print "$oauth_token|$oauth_secret|$oauth_confirm\n";
print "done!";

sub urlencode
{
  my ($url) = @_;

  $url =~ s/([^A-Za-z0-9_.-])/sprintf("%%%02X", ord($1))/seg;
  return $url;
}


1;

Friday, February 11, 2011

Login to twitter via backend using PERL

This is the same from the last post - Login to foursquare via backend using PERL but this time, we're doing it for twitter. Just follow the 4 simple steps below.

1. Install the libraries into your server.
  • LWP::UserAgent;
  • HTTP::Cookies;
2. Initialize the libraries UserAgent and Cookies.

my $lwpua = LWP::UserAgent->new;

my $user_agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ('Referer' => 'http://m.twitter.com',
             'User-Agent' => $user_agent);

my $cookie_file = "cookies.dat";
my $cookie_jar = HTTP::Cookies->new(
                file => $cookie_file,
                autosave => 1,
                ignore_discard => 1);

$lwpua->cookie_jar($cookie_jar);

3. Post your username and password to https://mobile.twitter.com/session and save the cookies.

my $strUser = '<your twitter username>';
my $strPass = '<your twitter password>';

# log-in to twitter
$response = $lwpua->post('https://mobile.twitter.com/session',
                            ['username' => $strUser,
                             'password' => $strPass,
                             'authenticity_token' => $auth_token], @header);

$cookie_jar->extract_cookies( $response );
$cookie_jar->save;

4. You can check if successful or not by accessing https://mobile.twitter.com via GET and print the content.

$response = $lwpua->get('https://mobile.twitter.com', @header);
$form_data = $response->content;

print "$form_data\n\ndone!";


That's it! Please see the complete code below.

#!/usr/bin/perl

require LWP::UserAgent;

use strict;
use warnings;

use HTTP::Cookies;

my $lwpua = LWP::UserAgent->new;

my $user_agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ('Referer' => 'http://m.twitter.com',
             'User-Agent' => $user_agent);

my $cookie_file = "cookies.dat";
my $cookie_jar = HTTP::Cookies->new(
                file => $cookie_file,
                autosave => 1,
                ignore_discard => 1);

$lwpua->cookie_jar($cookie_jar);

# getting authenticity token
my $response = $lwpua->get('https://mobile.twitter.com/session/new', @header);
my $form_data = $response->content;

$form_data =~ s/\n//g;
$form_data =~ /input name="authenticity_token" type="hidden" value="(.*?)"/ig;

my $auth_token = $1;

my $strUser = '<your twitter username>';
my $strPass = '<your twitter password>';

# log-in to twitter
$response = $lwpua->post('https://mobile.twitter.com/session',
                            ['username' => $strUser,
                             'password' => $strPass,
                             'authenticity_token' => $auth_token], @header);

$cookie_jar->extract_cookies( $response );
$cookie_jar->save;

$response = $lwpua->get('https://mobile.twitter.com', @header);
$form_data = $response->content;

print "$form_data\n\ndone!";


1;


Hope you like it!! Thank you for reading.

Tuesday, January 4, 2011

How to post tweet on twitter via backend using PERL

Just like from my previous post, you should know how the wap site works, from log-in up to sending your tweets.

If you still have no idea on how the twitter works, just follow the steps below and you will be able to send tweets in minutes.

1. Same on how we do it on facebook, we need to install the following libraries on our server.
  • LWP::UserAgent
  • HTTP::Cookies

2. Once installed, we are now ready to do the coding part. we have to require and initialize the libraries and variables that we will be using.

require LWP::UserAgent;

use strict;
use warnings;

use HTTP::Cookies;

my $lwpua = LWP::UserAgent->new;

my $user_agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ( 'Referer' => 'http://mobile.twitter.com/','User-Agent' => $user_agent);

my $cookie_file = "cookies.dat";
my $cookie_jar = HTTP::Cookies->new(
file => $cookie_file,
autosave => 1,
ignore_discard => 1);

$lwpua->cookie_jar($cookie_jar);


3. Input your twitter account username, password, and your tweet you wish to be posted.

my $strUser = "<your twitter username>";
my $strPass = "<your twitter password>";
my $strTweet = "<your tweet>";


4. Get the authenticity_token using REGEX from the twitter session url http://mobile.twitter.com/session/new. token will be use as parameter in submitting your credentials to the wap site. i also pasted the form element of the login page below as reference.

=begin
<form action="https://mobile.twitter.com/session" method="post">
<input name="authenticity_token" type="hidden" value="22a9872b3a17abd635a4" />
<input autocapitalize="off" autocorrect="off" id="username" name="username" type="text" />
<input id="password" name="password" type="password" />
<input class="signup" type="submit" value="Sign in" />
</form>
=cut

$form_data =~ s/\n//g;
$form_data =~ /input name="authenticity_token" type="hidden" value="(.*?)"/ig;

my $auth_token = $1;


5. Use the token to login by posting it to the form action url above: https://mobile.twitter.com/session and save the cookie for the nest session.

# logged in to twitter
$response = $lwpua->post('https://mobile.twitter.com/session',
['username' => $strUser,
'password' => $strPass,
'authenticity_token' => $auth_token], @header);

$cookie_jar->extract_cookies( $response );
$cookie_jar->save;

$response = $lwpua->get('http://mobile.twitter.com', @header);
$form_data = $response->content;


6. Upon submission of credentials, you should be able to log-in successfully. to check it, you should be able to see the "What's happenning?" and the textarea in which you will input your tweet. again, get the authenticity token using REGEX below for the next session.

=begin
<form action="http://mobile.twitter.com/" class="new_tweet" id="new_tweet" method="post">
<input name="authenticity_token" type="hidden" value="22a9872b3a17abd635a4" />
<div class="tweetbox-head">What's happening?</div>
<textarea class="tweet_input" cols="44" id="tweet_text" name="tweet[text]" rows="2"></textarea>
<input class="tweet-btns" type="submit" value="Tweet" />
</form>
=cut

$form_data =~ s/\n//g;
$form_data =~ /input name="authenticity_token" type="hidden" value="(.*?)"/ig;

$auth_token = $1;


7. And now, you are ready to post your tweet. by passing tweet[text] parameter together with the authenticity_token.

# posting tweet on twitter
@header = ( 'Referer' => 'http://mobile.twitter.com/', 'User-Agent' => $user_agent );
$response = $lwpua->post('http://mobile.twitter.com/',
['tweet[text]' => $strTweet,
'authenticity_token' => $auth_token], @header);

$form_data = $response->content;
unlink($cookie_file);


8. To get the complete code, please see below. hope you were able to follow. happy coding!!

#!/usr/bin/perl

require LWP::UserAgent;

use strict;
use warnings;

use HTTP::Cookies;

my $lwpua = LWP::UserAgent->new;

my $user_agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ( 'Referer' => 'http://mobile.twitter.com/','User-Agent' => $user_agent);

my $cookie_file = "cookies.dat";
my $cookie_jar = HTTP::Cookies->new(
file => $cookie_file,
autosave => 1,
ignore_discard => 1);

$lwpua->cookie_jar($cookie_jar);

my $strUser = "<your twitter username>";
my $strPass = "<your twitter password>";
my $strTweet = "<your tweet>";

# get authenticity token
my $response = $lwpua->get('http://mobile.twitter.com/session/new', @header);
my $form_data = $response->content;

$form_data =~ s/\n//g;
$form_data =~ /input name="authenticity_token" type="hidden" value="(.*?)"/ig;

my $auth_token = $1;

# logged in to twitter
$response = $lwpua->post('https://mobile.twitter.com/session',
['username' => $strUser,
'password' => $strPass,
'authenticity_token' => $auth_token], @header);

$cookie_jar->extract_cookies( $response );
$cookie_jar->save;

$response = $lwpua->get('http://mobile.twitter.com', @header);
$form_data = $response->content;

$form_data =~ s/\n//g;
$form_data =~ /input name="authenticity_token" type="hidden" value="(.*?)"/ig;

$auth_token = $1;

# posting tweet on twitter
@header = ( 'Referer' => 'http://mobile.twitter.com/', 'User-Agent' => $user_agent );
$response = $lwpua->post('http://mobile.twitter.com/',
['tweet[text]' => $strTweet,
'authenticity_token' => $auth_token], @header);

$form_data = $response->content;
unlink($cookie_file);



1;

Wednesday, December 22, 2010

Creating a twitter widget for your website

Copy the snippet inside <body></body> tag of your page, then change the username parameter on setUser call function.

You can also customize the look by changing the parameters under shell, tweets, and features. Ex. paulgonzaga

<script src="http://widgets.twimg.com/j/2/widget.js"></script> <script> new TWTR.Widget({ version: 2, type: 'profile', rpp: 3, interval: 6000, width: 'auto', height: 600, theme: { shell: { background: '#adadad', color: '#ffffff' }, tweets: { background: '#ffffff', color: '#2b2b2b', links: '#0735eb' } }, features: { scrollbar: false, loop: false, live: false, hashtags: true, timestamp: true, avatars: false, behavior: 'default' } }).render().setUser('paulgonzaga').start(); </script>

Leadership 101


  • Leadership demands sacrifices for the near-term to receive lasting benefits. the longer we wait to make sacrifices, the harder they become. Successful people make important decisions early in their life, then manage those decisions the rest of their lives.
  • Growth does not happen by chance. If you want to be sure to grow, you need a plan something strategic, specific, and scheduled. it's a discipline that would need incredible determination from us.
  • Success comes by going the extra mile, working the extra hours, and investing the extra time. The same is true for us. If we want to get to excel in any segment of life, a little extra effort can help. Our efforts can go a long way if we only work a little smarter, listen a little better, push a little harder, and persevere a little longer.
  • Making a difference in your work is not about productivity; it's about people. When you focus on others and connect with them, you can work together to accomplish great things.
  • Envision a goal you'd like to reach. Make it big enough to scare you a little. Now write down a plan for moving toward it. Create mini-goals within the big goal, to set yourself up for continual progress. And include some risks, too. Set yourself up for success.
  • Leaders build margins, not image. A leader may be forced to take unpopular stands for the good of the company. Popularity isn't bad, but decisions made solely on the basis of popular opinion can be devastating. So take courage and make the right though sometimes painful choices.