How to use Twitter API

To retrieve tweets of a twitter user into a website by specifying the number of tweet to be shown. This will not work if the user’s twitter account is not set to public.

HTML:

<div>
        <input class="name" placeholder="User's name"></input>
        <input class="num" placeholder="Number of tweet"></input>
        <button class="search">Search</button>
</div>
<div id="jstwitter"></div>

CSS:

#jstwitter {
    width: 400px;
    font-family: georgia;
    font-size: 15px;
    color: #333333;
}
#jstwitter .tweet {
    margin: 15px 0px 15px 0px;
    padding: 10px 10px 10px 10px;
    border-bottom: dotted 1px #ccc;
}
#jstwitter .tweet a {
    text-decoration: none;
    color: #13c9d0;
}
#jstwitter .tweet a:hover {
    text-decoration: underline;
}
#jstwitter .tweet .time {
    font-size: 10px;
    font-style: italic;
    color: #666666;
}

JQUERY(support 1.8.3):
There are 3 portions in the jquery code:
– loadTweets: This is how to use AJAX to call twitter API in JSON format and then process it and retrieve tweets.
– timeAgo: Relative calculator from twitter.
– ify: Convert twitter hashtag, alias, and links into hyperlinks.

$(document).ready(function () {
            $(".search").click(function () {
                // start jqtweet!
                JQTWEET = {
                    // Set twitter username, number of tweets &amp; id/class to append tweets
                    user: $(".name").val(),
                    numTweets: $(".num").val(),
                    appendTo: '#jstwitter',

                    // loadTweets: core function of jqtweet
                    loadTweets: function () {
                        $.ajax({
                            url: 'http://api.twitter.com/1.1/statuses/user_timeline.json/',
                            type: 'GET',
                            dataType: 'jsonp',
                            data: {
                                screen_name: JQTWEET.user,
                                include_rts: true,
                                count: JQTWEET.numTweets,
                                include_entities: true
                            },
                            success: function (data, textStatus, xhr) {

                                var html = '<div class="tweet">TWEET_TEXT<div class="time">AGO</div>';

                                // append tweets into page
                                for (var i = 0; i &lt; data.length; i++) {
                                    $(JQTWEET.appendTo).append(
                                    html.replace('TWEET_TEXT', JQTWEET.ify.clean(data[i].text))
                                        .replace(/USER/g, data[i].user.screen_name)
                                        .replace('AGO', JQTWEET.timeAgo(data[i].created_at))
                                        .replace(/ID/g, data[i].id_str));
                                }
                            }
                        });
                    },
                    //timeAgo
                    timeAgo: function (dateString) {
                        var rightNow = new Date();
                        var then = new Date(dateString);

                        if ($.browser.msie) {
                            // IE can't parse these crazy Ruby dates
                            then = Date.parse(dateString.replace(/( \+)/, ' UTC$1'));
                        }

                        var diff = rightNow - then;

                        var second = 1000,
                            minute = second * 60,
                            hour = minute * 60,
                            day = hour * 24,
                            week = day * 7;

                        if (isNaN(diff) || diff &lt; 0) {
                            return &quot;&quot;; // return blank string if unknown
                        }

                        if (diff &lt; second * 2) {
                            // within 2 seconds
                            return &quot;right now&quot;;
                        }

                        if (diff &lt; minute) {
                            return Math.floor(diff / second) + &quot; seconds ago&quot;;
                        }

                        if (diff &lt; minute * 2) {
                            return &quot;about 1 minute ago&quot;;
                        }

                        if (diff &lt; hour) {
                            return Math.floor(diff / minute) + &quot; minutes ago&quot;;
                        }

                        if (diff &lt; hour * 2) {
                            return &quot;about 1 hour ago&quot;;
                        }

                        if (diff  day &amp;&amp; diff &lt; day * 2) {
                            return &quot;yesterday&quot;;
                        }

                        if (diff &lt; day * 365) {
                            return Math.floor(diff / day) + &quot; days ago&quot;;
                        } else {
                            return &quot;over a year ago&quot;;
                        }
                    }, 
                    //ify
                    ify: {
                        link: function (tweet) {
                            return tweet.replace(/\b(((https*\:\/\/)|www\.)[^\&quot;\']+?)(([!?,.\)]+)?(\s|$))/g, function (link, m1, m2, m3, m4) {
                                var http = m2.match(/w/) ? 'http://' : '';
                                return '<a class="twtr-hyperlink" target="_blank" href="' + http + m1 + '">' + ((m1.length &gt; 25) ? m1.substr(0, 24) + '...' : m1) + '</a>' + m4;
                            });
                        },

                        at: function (tweet) {
                            return tweet.replace(/\B[@@]([a-zA-Z0-9_]{1,20})/g, function (m, username) {
                                return '<a target="_blank" class="twtr-atreply" href="http://twitter.com/intent/user?screen_name=' + username + '">@' + username + '</a>';
                            });
                        },

                        list: function (tweet) {
                            return tweet.replace(/\B[@@]([a-zA-Z0-9_]{1,20}\/\w+)/g, function (m, userlist) {
                                return '<a target="_blank" class="twtr-atreply" href="http://twitter.com/' + userlist + '">@' + userlist + '</a>';
                            });
                        },

                        hash: function (tweet) {
                            return tweet.replace(/(^|\s+)#(\w+)/gi, function (m, before, hash) {
                                return before + '<a target="_blank" class="twtr-hashtag" href="http://twitter.com/search?q=%23' + hash + '">#' + hash + '</a>';
                            });
                        },

                        clean: function (tweet) {
                            return this.hash(this.at(this.list(this.link(tweet))));
                        }
                    } 
                };
                $("#jstwitter").empty(); 
                JQTWEET.loadTweets();
            });
        });

SAMPLE OUTPUT:
New Picture (10)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s