Skip to Content

DIC52 Week 3: Twitter API Syndicate content

Dave Sherohman's picture

This week is something of a gimme for me, given that I've already done app development against the Twitter API. For the sake of something simple and accessible, I opted to revise my earlier Iron Man post on Monitoring Hashtags with Perl and Net::Twitter to make use of Twitter::TagGrep and call that my DIC 52 Weeks of Code entry for this week:

#!/usr/bin/perl

use strict;
use warnings;

use Net::Twitter;
use Twitter::TagGrep;

my $user = 'username';
my $pass = 'password;

my $twit = Net::Twitter->new( { username => $user,
                                password => $pass } );
my $tg = Twitter::TagGrep->new( prefix => '#!',
                                tags   => [ 'perl', 'dic52', 'win' ] );

# $last_seen needs to be initialized to a positive value because
# Twitter does not respond properly when given a since_id of 0
my $last_seen = 1;
my $check_interval = 600; # seconds

while ($twit) {
  $last_seen = print_new_hits($twit, $tg, $last_seen);
  sleep $check_interval;
}

exit;


sub print_new_hits {
  my ($twit, $tg, $last_seen) = @_;

  my $timeline = $twit->friends_timeline( { count    => 200,
                                            since_id => $last_seen } );
  return $last_seen unless $timeline->[0];

  $last_seen = $timeline->[0]->{id};
  my @hits = $tg->grep_tags($timeline);

  for my $tweet (reverse @hits) {  # reverse @hits to show oldest first
    my $screen_name     = $tweet->{user}->{screen_name};
    my $text            = $tweet->{text};
    my $time            = $tweet->{created_at};
    print "$screen_name ($time)\n$text\n\n";
  }

  return $last_seen;
}

As with the original version, you need to substitute your own Twitter username and password for it to connect successfully.

Configured as shown here, it will check your Twitter friends timeline once every 10 minutes (to avoid rate limiting issues) and display any status updates containing the tags #perl, #dic52, #win, !perl, !dic52, or !win. (I'm not actually sure where the !bangtags are from, but I see a lot of people using !perl instead of #perl.)

The call to create the Net::Twitter instance is using an older form of the constructor. This is deliberate, as it allows the code as presented here to work with both 2.x (pre-Moose) and 3.x (Moose-based) versions of Net::Twitter. If you want to use OAuth instead of Basic Authentication, I highly recommend using Net::Twitter 3.x and the newer-style constructor.

Post new comment