Often called a revolution, Twitter is a very easy and cool way to communicate and promote your blog or service. In this article, I have compiled 10 very useful code snippets to interact with Twitter in your web dev projects.

1 – Autofollow script (PHP)

This code allow you to automatically follow user who have tweeted about a specific term. For example, if you want to follow all users who tweeted about php, simply give it as a value to the $term variable on line 7.

<?php
// Twitter Auto-follow Script by Dave Stevens - http://davestevens.co.uk 

$user = "";
$pass = "";

$term = "";

$userApiUrl = "http://twitter.com/statuses/friends.json";

$ch = curl_init($userApiUrl);
curl_setopt($ch, CURLOPT_USERPWD, $user.":".$pass);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$apiresponse = curl_exec($ch);
curl_close($ch);
$followed = array();

if ($apiresponse) {
	$json = json_decode($apiresponse);
	if ($json != null) {
		foreach ($json as $u) {
			$followed[] = $u->name;
		}
	}
}

$userApiUrl = "http://search.twitter.com/search.json?q=" . $term . "&rpp=100";
$ch = curl_init($userApiUrl);
curl_setopt($ch, CURLOPT_USERPWD, $user.":".$pass);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$apiresponse = curl_exec($ch);
curl_close($ch);

if ($apiresponse) {
	$results = json_decode($apiresponse);
	$count = 20;
	if ($results != null) {
		$resultsArr = $results->results;
		if (is_array($resultsArr)) {
			foreach ($resultsArr as $result) {
				$from_user = $result->from_user;
				if (!in_array($from_user,$followed)) {
					$ch = curl_init("http://twitter.com/friendships/create/" . $from_user . ".json");
					curl_setopt($ch, CURLOPT_USERPWD, $user.":".$pass);
					curl_setopt($ch, CURLOPT_POST, 1);
					curl_setopt($ch, CURLOPT_POSTFIELDS,"follow=true");
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
					$apiresponse = curl_exec($ch);

					if ($apiresponse) {
						$response = json_decode($apiresponse);
						if ($response != null) {
							if (property_exists($response,"following")) {
								if ($response->following === true) {
									echo "Now following " . $response->screen_name . "\n";
								} else {
									echo "Couldn't follow " . $response->screen_name . "\n";
								}
							} else {
								echo "Follow limit exceeded, skipped " . $from_user . "\n";
							}
						}
					}
					curl_close($ch);
				} else {
					echo "Already following " . $from_user . "\n";
				}
			}
		}
	}
}
?>

Source : http://snipplr.com/view/17595/twitter-autofollow-php-script/

2 – Get the number of follower in full text (PHP)

When you have a website or blog and use Twitter, it can be cool to display how many followers you have. To do so, simply use the short code snippet above.
Note that if you want to integrate the same code into WordPress, using caching, Rarst have written a nice code that you can get using the link after the snippets (Rarst code is in the comments, so scroll down a bit)

<?php
$xml=file_get_contents('http://twitter.com/users/show.xml?screen_name=catswhocode');
if (preg_match('/followers_count>(.*)</',$xml,$match)!=0) {
	$tw['count'] = $match[1];
}
echo $tw['count'];
?>

Source : Rarst on http://www.wprecipes.com/display-the-total-number-of-your-twitter-followers-on-your-wordpress-blog

3 – View who doesn’t follow you (Python)

Some people don’t like the idea of following people who don’t follow you back. If you recognized yourself in this statement, there’s a huge amount of chances that you’ll enjoy the following Python code snippet.
Simply type your Twitter username and password on line 4 and call the file using the Python interpreter.

import twitter, sys, getpass, os

def call_api(username,password):
    api = twitter.Api(username,password)
    friends = api.GetFriends()
    followers = api.GetFollowers()
    heathens = filter(lambda x: x not in followers,friends)
    print "There are %i people you follow who do not follow you:" % len(heathens)
    for heathen in heathens:
        print heathen.screen_name

if __name__ == "__main__":
    password = getpass.getpass()
    call_api(sys.argv[1], password)

Source : http://blog.davidziegler.net/post/107429458/see-which-twitterers-don-t-follow-you-back-in-less-than

4 – Update your Twitter status…using Vim

The Vim editor is one of the most powerful and complete text editor available. This command, allowing you to update your Twitter status, is just one more proof.
Oh and don’t forget to check out our list of 100 Vim commands that every developer should know

command -range Twitter
,
write ++enc=UTF-8 !curl --data-urlencode status@- --netrc --no-remote-name http://twitter.com/statuses/update.xml

Source : http://snipplr.com/view/16550/vim-command-to-post-to-twitter/

5 – Get Your Most Recent Twitter Status (PHP)

A simple PHP function that get your latest Twitter status so you can display it on your blog or website.

<?php
function get_status($twitter_id, $hyperlinks = true) {
    $c = curl_init();
    curl_setopt($c, CURLOPT_URL, "http://twitter.com/statuses/user_timeline/$twitter_id.xml?count=1");
    curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
    $src = curl_exec($c);
    curl_close($c);
    preg_match('/<text>(.*)<\/text>/', $src, $m);
    $status = htmlentities($m[1]);
    if( $hyperlinks ) $status = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", "<a href=\"\\0\">\\0</a>", $status);
    return($status);
}
?>

Source : http://abeautifulsite.net/notebook/75

6 – Twitter email grabber (PHP)

You know it, you sould never type your email adress on the Internet. This include Twitter. Due to the site popularity, lots of spammers created scripts to grab email adresses from the site. How can they do that? Like that:

<?php
$file = file_get_contents("http://search.twitter.com/search?q=gmail.com+OR+hotmail.com++OR+%22email+me%22");
$file = strip_tags($file);

preg_match_all(
    "([a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum)\b)siU",
    $file,
    $matches);

print_r($matches);
?>

Source : http://www.fromzerotoseo.com/twitter-email-grabber/

7 – Backup your tweets (Ruby)

Are you a Ruby programmer who always wanted to be able to keep a backup of his tweets? If yes, you’ll love this snippet.

#! /usr/bin/ruby

require 'rubygems'
require 'json'
require 'net/http'
require 'uri'

class TwitterBackup

  def backup(username)
    url = URI::parse('http://twitter.com')

    page = 1
    loop do
      req = Net::HTTP::Get.new("/statuses/user_timeline.json?screen_name=#{username}&count=200&page=#{page}")
      res = Net::HTTP.start(url.host, url.port) {|http| http.request(req) }

      if res.body.length > 2
        process_response(JSON.parse(res.body))
      else
        break
      end

      page += 1
    end
  end

  protected
    def process_response(response_json)
        response_json.each do |tweet|
          puts "#{Time.parse(tweet['created_at']).strftime("%A %d %B %Y at %I:%M%p")}, #{tweet['text']}, #{tweet['source']}, #{tweet['in_reply_to_screen_name']}"
        end
    end
end

TwitterBackup.new.backup(ARGV[0])

To run, save as twitterbackup.rb and launch from the command line:

ruby twitterbackup.rb yourtwittername

Source : http://snipplr.com/view.php?codeview&id=19107

8 – Timeline function (PHP)

Since Twitter became very popular, I started to hear many people saying that they absolutely love how Twitter display time informations: 1 hour ago, about 7 days ago, less than a minute ago, etc. This is what the function below do.

function timespan($time1, $time2 = NULL, $output = 'years,months,weeks,days,hours,minutes,seconds')
{
	$output = preg_split('/[^a-z]+/', strtolower((string) $output));
	if (empty($output))
		return FALSE;
	extract(array_flip($output), EXTR_SKIP);
	$time1  = max(0, (int) $time1);
	$time2  = empty($time2) ? time() : max(0, (int) $time2);
	$timespan = abs($time1 - $time2);
	isset($years) and $timespan -= 31556926 * ($years = (int) floor($timespan / 31556926));
	isset($months) and $timespan -= 2629744 * ($months = (int) floor($timespan / 2629743.83));
	isset($weeks) and $timespan -= 604800 * ($weeks = (int) floor($timespan / 604800));
	isset($days) and $timespan -= 86400 * ($days = (int) floor($timespan / 86400));
	isset($hours) and $timespan -= 3600 * ($hours = (int) floor($timespan / 3600));
	isset($minutes) and $timespan -= 60 * ($minutes = (int) floor($timespan / 60));
	isset($seconds) and $seconds = $timespan;
	unset($timespan, $time1, $time2);
	$deny = array_flip(array('deny', 'key', 'difference', 'output'));
	$difference = array();
	foreach ($output as $key) {
		if (isset($$key) AND ! isset($deny[$key])) {
			$difference[$key] = $$key;
		}
	}
	if (empty($difference))
		return FALSE;
	if (count($difference) === 1)
		return current($difference);
	return $difference;
}

Source : http://snipplr.com/view.php?codeview&id=19353

9 – Display your Twitter entries on your WordPress blog

Integrating a RSS feed is easy, but it is even more on a WordPress blog. The following code allow you to display your 5 most recent Twitter entries on your WordPress blog.

<?php include_once(ABSPATH . WPINC . '/rss.php');
wp_rss('http://twitter.com/statuses/user_timeline/15985955.rss', 5); ?>

Source : http://www.wprecipes.com/how-to-display-any-rss-feed-on-your-wordpress-blog

10 – RSS to Twitter (PHP)

This script isn’t exactly new, but yet, it is still very usefull and this is why I decided to include it in this article. Due to the size of this code, I’m not going to display it on here. You can grab access instructions and download it from the original source.

Source : http://paulstamatiou.com/stammy-script-rss-to-twitter-using-php/

 

45 Comments

  1. Posted September 14, 2009 at 7:08 pm | Permalink

    A nice list. A few of them will definitely come in handy. I used one from the lylo files which I modified for myself. It displays up to 20 tweets and also displays #hashtags, @replys and urls as well as date in various formats.

  2. Posted September 14, 2009 at 8:50 pm | Permalink

    Nice collection. I made a few little twitter apps in the past, and must say I do like the way twitter set up their API. Works pretty simply.

  3. Posted September 14, 2009 at 9:14 pm | Permalink

    Thanks! I’m now using the PHP function to get the numbers of followers.

    Such a pity that the function to backup tweets is written in Ruby. :(
    I’m desperately searching for a way to archive my tweets automatically in my WordPress blog. Unfortunately I can’t manage to get the Twitter Tools plugin working correctly, it seems to be a common problem…

  4. Posted September 14, 2009 at 9:51 pm | Permalink

    useful collection..thanks

  5. Posted September 14, 2009 at 10:40 pm | Permalink

    Useful and informative compilation as always!

  6. Posted September 15, 2009 at 1:54 am | Permalink

    it’s a great list, but will more good if there are an example.

  7. Posted September 15, 2009 at 3:31 am | Permalink

    Thanks for the snippets! I’ll be sure to use them.

    For number 3, you should remember to download some twitter module. I tried typing ‘import twitter’ into the interactive terminal, and it seems that it didn’t exist. It would actually be surprising for Python to come with a Twitter module.

  8. Posted September 15, 2009 at 7:54 am | Permalink
  9. Posted September 15, 2009 at 1:35 pm | Permalink

    Cool, thanks. Love this site!

  10. Posted September 16, 2009 at 9:27 am | Permalink

    The first script rocks. Thanks! Very useful!

  11. Posted September 16, 2009 at 12:58 pm | Permalink

    Just dugg you mate….thanks for such an exceptional post….really speaking it would be really helpful for many of us.

  12. Posted September 16, 2009 at 7:07 pm | Permalink

    A variation on the first script using the Zend Framework. The difference is you can auto-follow followers from another person.

    http://blog.corywiles.com/automate-adding-twitter-followers-with-zend-f

  13. Posted September 16, 2009 at 10:48 pm | Permalink

    file_get_contents() and json_decode() are your friends:

    $c=json_decode(file_get_contents(”http://twitter.com/statuses/user_timeline/”.urlencode($username).”.json”));echo $c[0]->text;

  14. Kennedy
    Posted September 17, 2009 at 3:06 am | Permalink

    I filled in my user name, password, and term. cURL is enabled.
    I recive this error Fatal error: Call to undefined function: json_decode() in /home/content/s/i/x/sixcells/html/follow.php on line 20

  15. Posted September 17, 2009 at 8:22 am | Permalink

    Ultimate post buddy, Now I can remove atleast two plugins from my blog which are currently showing recent tweets and number of followers. Thanks a lot buddy for this exceptionally best post related to twitter.

  16. Posted September 17, 2009 at 9:24 pm | Permalink

    Wow! This post is just full of some awesome tools that I will start implementing now. Also, I would love a quick guide on Twitter apps too lol

  17. Posted September 18, 2009 at 11:40 pm | Permalink

    Awesome post, A-level quality of information.

    Totally thankful !!

  18. Posted September 21, 2009 at 8:21 am | Permalink

    Good list thank you very much! :) I`ll try these tips.

  19. Garrapata
    Posted September 21, 2009 at 7:04 pm | Permalink

    All of these are good examples to get something working quickly, but there are better ways to interact with twitter. For instance, you can create a single function that makes the call to the api so that you don’t repeat the same code every time. I found a great example here: sourcecookbook.com/en/recipes/50/how-to-communicate-with-the-twitter-api-in-php-extremely-easy

  20. Posted September 22, 2009 at 8:24 am | Permalink

    Great list of code snippets for twitter. Definitely, these codes will be very useful to users. Now, you can easily tie up your twitter account to your site.

  21. Posted September 22, 2009 at 10:44 am | Permalink

    Just a short while ago – on the 14th – a new PEAR package, http://pear.php.net/package/Services_Twitter , was released that offers a lot of twitter related functionality that your describing here that can be utilised anywhere PHP is used.

  22. Posted September 22, 2009 at 5:47 pm | Permalink

    @Ken Guest: Thanks for letting me know I’m going to check it out!

  23. Posted September 22, 2009 at 10:43 pm | Permalink

    Interesting post! Nice collection of useful tips!

  24. Posted September 24, 2009 at 4:53 pm | Permalink

    Thanks Jean-Baptiste Jung! Nice post and thanks Ken Guest for PEAR package.

  25. Posted September 24, 2009 at 7:47 pm | Permalink

    Hey… there is so much you can do with twitter…
    Interesting

  26. Posted September 24, 2009 at 11:53 pm | Permalink

    It’d be awesome if somebody could help me with number 1. I’m wanting to build a tool for personal use but dont know anything about curl, very little about the twitter apis and not a ton about php. are there any tutorials out there about this script or one similar doing the same function/idea?

    thanks for the help!

  27. Posted September 30, 2009 at 8:44 am | Permalink

    Yeah the post image says it right. Awesome! ;)

  28. Posted September 30, 2009 at 11:30 am | Permalink

    lot’s of code here, thanks for sharing that, i will try at my twitter…

    Dini

  29. Posted September 30, 2009 at 3:17 pm | Permalink

    Wow!!! Very very very very useful , i’m favorite this entry.
    Thanks

  30. Posted October 1, 2009 at 7:25 pm | Permalink

    Helpful collection of snippets. Will take advantage of the Autofollow script for sure.
    Thanks!

  31. Posted October 10, 2009 at 1:20 pm | Permalink

    Wonderful collection of code snippets. Thanks for sharing.

  32. Posted October 10, 2009 at 9:47 pm | Permalink

    Very Nice Information.

    First Code is Rock ;0)

  33. Posted October 12, 2009 at 4:47 am | Permalink

    Thanks for posting the codes. Got an answer here.. I will bookmark this for reference.

  34. Posted October 14, 2009 at 9:51 pm | Permalink

    Oh!!
    My brain hurts… The info……. Awesome!

    I thank you for the time putting this website together!
    I have just discovered it today, I have a lot of work to do.

    I can not program, yet I can compy and paste code and then change it a bit (with in reason)

    Thanks
    Lori

  35. Posted October 28, 2009 at 2:31 am | Permalink

    I updated my php today and it now works.

  36. Posted November 1, 2009 at 12:19 pm | Permalink

    Most of the codes are a bit too hard for me to implement on my future Twitter. Guess I’ll need a helping hand. But thanks for sharing such informative tips!

  37. Posted November 6, 2009 at 6:31 pm | Permalink

    Thanks for this.. it is great help for us sharing your idea in PHP code.

  38. Posted November 7, 2009 at 1:13 am | Permalink

    Loved the code to tell how many followers you have. I don’t see much of a point to this code other then bragging. Still thanks for posting it for us.

  39. Posted November 25, 2009 at 11:08 am | Permalink

    Cool!

  40. Posted November 25, 2009 at 2:25 pm | Permalink

    I would really like an extend to this script, so I can use the most resent twitter status with a specific tag (for example #site). Just like LinkedIn is using #in right now. Some suggestions on where to find such a script?

    5 – Get Your Most Recent Twitter Status (PHP)
    - extension: filter specific tag like LinkedIn does

  41. Posted November 26, 2009 at 11:25 pm | Permalink

    Thanks for the code, i need to bookmarked this stuff for my future reference!

  42. Posted December 3, 2009 at 5:14 am | Permalink

    Amazing, I’ll Give it a Try!

  43. Posted December 4, 2009 at 4:01 pm | Permalink

    Thanks for the code! Well, let me try this!

  44. Posted December 6, 2009 at 5:31 pm | Permalink

    Hey, I try this last week and it works!! Thanks for the brilliant codes…

  45. john
    Posted January 24, 2010 at 5:56 pm | Permalink

    hi, I am having problem about json_decode with cursoration,
    $userApiUrl = “http://twitter.com/statuses/friends.json?cursor=-1″;

    is this correct:
    $followed[] = $u->users->name; to get my friend’s name? i am doing this but it does not returns anything. and also this one:
    $json = json_decode($apiresponse);
    if ($json != null) {
    foreach ($json as $u) {
    $cursor1 = $u->next_cursor_str;
    $followed[] = $u->users->name

    how can I get it to work?

30 Trackbacks

  1. [...] 10 code snippets to interact with Twitter Share and Enjoy: [...]

  2. By 10 code snippets to interact with Twitter | TopRoundups on September 15, 2009 at 12:10 am

    [...] 10 code snippets to interact with Twitter Submitted by Editorial Team [...]

  3. [...] 10 Code Snippets to Interact with Twitter [...]

  4. By Lesenswertes vom Tuesday, 15. September 2009 : MiZine on September 16, 2009 at 12:02 am

    [...] 10 code snippets to interact with Twitter 10 Code-Schnipsel für Interaktionen mit Twitter via PHP, VIm, Ruby, WordPress Tags: Code Schnipsel Twitter PHP WordPress [...]

  5. [...] CatsWhoCode.com blog has posted ten PHP code snippets that can help you connect with Twitter and perform certain actions [...]

  6. [...] 10 code snippets to interact with Twitter 10 code snippets to interact with Twitter [...]

  7. By Daily Digest for 2009-09-17 | Pedro Trindade on September 18, 2009 at 9:12 am

    [...] 10 code snippets to interact with Twitter [...]

  8. [...] CatsWhoCode.com blog has posted ten PHP code snippets that can help you connect with Twitter and perform certain actions [...]

  9. [...] 10 code snippets to interact with Twitter Twitterを使う関数のサンプル [...]

  10. By BlogBuzz September 19, 2009 on September 19, 2009 at 12:17 pm

    [...] 10 code snippets to interact with Twitter [...]

  11. [...] Source:10 code snippets to interact with Twitter [...]

  12. [...] Your Own Server Posted by tuxwire on September 23rd, 2009 No Comments Printer-Friendly In the 10 code snippets to interact with Twitter by CatsWhoCode, I found an interesting PHP script which can be used to auto-follow people on [...]

  13. By This Week in Twitter for 9/25/2009 « Church Mojo on September 25, 2009 at 5:10 pm

    [...] 10 Code Snippets to Interact with Twitter Add some Twitter goodness to your church site in PHP, Ruby or PASCAL. Maybe not PASCAL, but it sounds so French and the author, Jean-Baptiste Jung, is from the French speaking part of Belgium. [...]

  14. [...] Enlace: 10 code snippets to interact with Twitter [...]

  15. [...] 10 code snippets to interact with Twitter [...]

  16. [...] Official Link [...]

  17. [...] Official Link [...]

  18. [...] and using .htaccess – An Intro for Web Designers 10 Things a Web Designer Should Consider 10 code snippets to interact with Twitter Easy Custom Feeds in WordPress 32 Most Useful Worpdress Comments Page Hacks 10 useful Wordpress [...]

  19. [...] 10 code snippets to interact with Twitter [...]

  20. [...] 10 code snippets to interact with Twitter (tags: twitter php code api scripts python autofollow backup wordpress) AKPC_IDS += "365,";Popularity: unranked [?] [...]

  21. By BlogMouth : Twitter Tweet Links September 2009 on October 5, 2009 at 11:29 pm

    [...] 10 code snippets to interact with Twitter [...]

  22. [...] 10 code snippets to interact with Twitter [...]

  23. By Mes favoris du 24-11-09 au 25-11-09 on November 25, 2009 at 11:44 am

    [...] 10 code snippets to interact with Twitter  [...]

  24. By links for 2009-11-25 | Eric Reboisson's Blog on November 25, 2009 at 10:05 pm

    [...] 10 code snippets to interact with Twitter (tags: twitter scripts) Tags: AJAX, application, blog, code, free, Links, plugin, software, top, twitter Commentaires (0) [...]

  25. [...] статьи на сайте Cats Who Code.com. Я выбрал только те функции, которые мне были [...]

  26. [...] Achei um jeito mais fácil aqui. [...]

  27. By Twitter automatisieren! | My IT-Blog on February 9, 2010 at 3:50 am

    [...] Auf folgender Webseite (www.catswhocode.com) habe ich ein paar sehr interessante PHP-Skript gefunden, eines davon stelle ich hier kurz vor.Das [...]

  28. [...] tweetmeme_url = "http://www.catswhocode.com/blog/10-code-snippets-to-interact-with-twitter"; tweetmeme_style = "compact"; isquare Read Post [...]

  29. [...] snippets to interact with Twitter Filed under: web-development — admin @ 10:38 pm isquare Read Post Often called a revolution, Twitter is a very easy and cool way to communicate and promote your [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Subscribe without commenting

  • Smashing Network
WordPress Appliance - Powered by TurnKey Linux