10 $Data::Dumper::Indent = 1;
12 use vars qw($VERSION %IRSSI);
15 my ($REV) = '$Rev: 333 $' =~ /(\d+)/;
17 authors => 'Dan Boger',
18 contact => 'zigdon@gmail.com',
20 description => 'Send twitter updates using /tweet. '
21 . 'Can optionally set your bitlbee /away message to same',
22 license => 'GNU GPL v2',
23 url => 'http://tinyurl.com/twirssi',
24 changed => 'Mon Dec 1 15:36:01 PST 2008',
34 my $last_poll = time - 300;
39 my ( $data, $server, $win ) = @_;
42 ¬ice("Not logged in! Use /twitter_login username pass!");
46 my ( $target, $text ) = split ' ', $data, 2;
47 unless ( $target and $text ) {
48 ¬ice("Usage: /dm <nick> <message>");
52 &cmd_direct_as( "$user $data", $server, $win );
56 my ( $data, $server, $win ) = @_;
59 ¬ice("Not logged in! Use /twitter_login username pass!");
63 my ( $username, $target, $text ) = split ' ', $data, 3;
64 unless ( $username and $target and $text ) {
65 ¬ice("Usage: /dm_as <username> <nick> <message>");
69 unless ( exists $twits{$username} ) {
70 ¬ice("Unknown username $username");
74 unless ( $twits{$username}
75 ->new_direct_message( { user => $target, text => $text } ) )
77 ¬ice("DM to $target failed");
81 ¬ice("DM sent to $target");
82 $nicks{$target} = time;
86 my ( $data, $server, $win ) = @_;
89 ¬ice("Not logged in! Use /twitter_login username pass!");
93 $data =~ s/^\s+|\s+$//;
95 ¬ice("Usage: /tweet <update>");
99 &cmd_tweet_as( "$user $data", $server, $win );
103 my ( $data, $server, $win ) = @_;
106 ¬ice("Not logged in! Use /twitter_login username pass!");
110 $data =~ s/^\s+|\s+$//;
111 my ( $username, $data ) = split ' ', $data, 2;
113 unless ( $username and $data ) {
114 ¬ice("Usage: /tweet_as <username> <update>");
118 unless ( exists $twits{$username} ) {
119 ¬ice("Unknown username $username");
123 if ( Irssi::settings_get_str("short_url_provider") ) {
124 foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
126 my $short = makeashorterlink($url);
127 $data =~ s/\Q$url/$short/g;
132 if ( length $data > 140 ) {
134 "Tweet too long (" . length($data) . " characters) - aborted" );
138 unless ( $twits{$username}->update($data) ) {
139 ¬ice("Update failed");
143 foreach ( $data =~ /@([-\w]+)/ ) {
148 if ( Irssi::settings_get_bool("tweet_to_away")
150 and $data !~ /^[dD] / )
153 Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
155 $server->send_raw("away :$data");
158 ¬ice( "Can't find bitlbee server.",
159 "Update bitlbee_server or disalbe tweet_to_away" );
163 ¬ice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
167 my ( $usage_str, $api_name, $post_ref ) = @_;
170 my ( $data, $server, $win ) = @_;
173 ¬ice("Not logged in! Use /twitter_login username pass!");
177 $data =~ s/^\s+|\s+$//;
179 ¬ice("Usage: $usage_str");
183 unless ( $twit->$api_name($data) ) {
184 ¬ice("$api_name failed");
188 &$post_ref($data) if $post_ref;
193 my ( $data, $server, $win ) = @_;
195 $data =~ s/^\s+|\s+$//g;
196 if ( exists $twits{$data} ) {
197 ¬ice("Switching to $data");
198 $twit = $twits{$data};
201 ¬ice("Unknown user $data");
206 my ( $data, $server, $win ) = @_;
208 $data =~ s/^\s+|\s+$//g;
209 if ( $data and exists $twits{$data} ) {
210 ¬ice("Logging out $data...");
211 $twits{$data}->end_session();
212 delete $twits{$data};
214 ¬ice("Unknown username '$data'");
216 ¬ice("Logging out $user...");
217 $twit->end_session();
219 delete $twits{$user};
221 &cmd_switch( ( keys %twits )[0], $server, $win );
223 Irssi::timeout_remove($poll) if $poll;
230 my ( $data, $server, $win ) = @_;
233 ( $user, $pass ) = split ' ', $data, 2;
234 } elsif ( my $autouser = Irssi::settings_get_str("twitter_usernames")
235 and my $autopass = Irssi::settings_get_str("twitter_passwords") )
237 my @user = split /\s*,\s*/, $autouser;
238 my @pass = split /\s*,\s*/, $autopass;
239 if ( @user != @pass ) {
240 ¬ice("Number of usernames doesn't match "
241 . "the number of passwords - auto-login failed" );
244 while ( @user and @pass ) {
252 ¬ice("/twitter_login requires either a username and password "
253 . "or twitter_usernames and twitter_passwords to be set." );
257 %friends = %nicks = ();
259 $twit = Net::Twitter->new(
265 unless ( $twit->verify_credentials() ) {
266 ¬ice("Login as $user failed");
269 &cmd_switch( ( keys %twits )[0], $server, $win );
275 my $rate_limit = $twit->rate_limit_status();
276 if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
277 ¬ice("Rate limit exceeded, try again later");
282 $twits{$user} = $twit;
283 Irssi::timeout_remove($poll) if $poll;
284 $poll = Irssi::timeout_add( 300 * 1000, \&get_updates, "" );
285 ¬ice("Logged in as $user, loading friends list...");
287 ¬ice( "loaded friends: ", scalar keys %friends );
288 if ( Irssi::settings_get_bool("twirssi_first_run") ) {
289 Irssi::settings_set_bool( "twirssi_first_run", 0 );
290 unless ( exists $friends{twirssi} ) {
291 ¬ice("Welcome to twirssi!"
292 . " Perhaps you should add \@twirssi to your friends list,"
293 . " so you can be notified when a new version is release?"
294 . " Just type /twitter_friend twirssi." );
301 ¬ice("Login failed");
306 my ( $data, $server, $win ) = @_;
308 my $loc = Irssi::settings_get_str("twirssi_location");
311 "$loc isn't writable, can't upgrade. Perhaps you need to /set twirssi_location?"
316 if ( not -x "/usr/bin/md5sum" and not $data ) {
318 "/usr/bin/md5sum can't be found - try '/twirssi_upgrade nomd5' to skip MD5 verification"
325 eval { use Digest::MD5; };
329 "Failed to load Digest::MD5. Try '/twirssi_upgrade nomd5' to skip MD5 verification"
334 $md5 = get("http://twirssi.com/md5sum");
338 ¬ice("Failed to download md5sum from peeron! Aborting.");
342 unless ( open( CUR, $loc ) ) {
344 "Failed to read $loc. Check that /set twirssi_location is set to the correct location."
349 my $cur_md5 = Digest::MD5::md5_hex(<CUR>);
352 if ( $cur_md5 eq $md5 ) {
353 ¬ice("Current twirssi seems to be up to date.");
358 my $URL = "http://twirssi.com/twirssi.pl";
359 ¬ice("Downloading twirssi from $URL");
360 LWP::Simple::getstore( $URL, "$loc.upgrade" );
363 unless ( open( NEW, "$loc.upgrade" ) ) {
365 "Failed to read $loc.upgrade. Check that /set twirssi_location is set to the correct location."
370 my $new_md5 = Digest::MD5::md5_hex(<NEW>);
373 if ( $new_md5 ne $md5 ) {
374 ¬ice("MD5 verification failed. expected $md5, got $new_md5");
379 rename $loc, "$loc.backup"
380 or ¬ice("Failed to back up $loc: $!. Aborting")
382 rename "$loc.upgrade", $loc
383 or ¬ice("Failed to rename $loc.upgrade: $!. Aborting")
386 my ( $dir, $file ) = ( $loc =~ m{(.*)/([^/]+)$} );
387 if ( -e "$dir/autorun/$file" ) {
388 ¬ice("Updating $dir/autorun/$file");
389 unlink "$dir/autorun/$file"
390 or ¬ice("Failed to remove old $file from autorun: $!");
391 symlink "../$file", "$dir/autorun/$file"
392 or ¬ice("Failed to create symlink in autorun directory: $!");
395 ¬ice("Download complete. Reload twirssi with /script load $file");
403 print $fh "Loading friends page $page...\n" if ($fh and &debug);
404 my $friends = $twit->friends( { page => $page } );
405 last unless $friends;
406 $new_friends{ $_->{screen_name} } = time foreach @$friends;
408 last if @$friends == 0 or $page == 10;
411 my ($added, $removed) = (0, 0);
412 print $fh "Scanning for new friends...\n" if ($fh and &debug);
413 foreach ( keys %new_friends ) {
414 next if exists $friends{$_};
419 print $fh "Scanning for removed friends...\n" if ($fh and &debug);
420 foreach ( keys %friends ) {
421 next if exists $new_friends{$_};
426 return ($added, $removed);
430 print scalar localtime, " - get_updates starting" if &debug;
433 Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
436 ->print( "Can't find a window named '"
437 . Irssi::settings_get_str('twitter_window')
438 . "'. Create it or change the value of twitter_window" );
441 ¬ice("Not logged in! Use /twitter_login username pass!");
445 my ( $fh, $filename ) = File::Temp::tempfile();
449 Irssi::timeout_add_once( 5000, 'monitor_child', [$filename] );
450 Irssi::pidwait_add($pid);
451 } elsif ( defined $pid ) { # child
458 &do_updates( $fh, $user, $twit );
459 foreach ( keys %twits ) {
461 &do_updates( $fh, $_, $twits{$_} );
464 my ($added, $removed) = &load_friends($fh);
465 if ($added + $removed) {
466 print $fh "%R***%n Friends list updated: ",
467 join(", ", sprintf("%d added", $added),
468 sprintf("%d removed", $removed)), "\n";
470 print $fh "__friends__\n";
471 foreach ( sort keys %friends ) {
472 print $fh "$_ $friends{$_}\n";
478 print scalar localtime, " - get_updates ends" if &debug;
482 my ( $fh, $username, $obj ) = @_;
484 print scalar localtime, " - Polling for updates for $username" if &debug;
486 $obj->friends_timeline( { since => HTTP::Date::time2str($last_poll) } )
488 foreach my $t ( reverse @$tweets ) {
489 my $text = decode_entities( $t->{text} );
491 $text =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
493 if ( Irssi::settings_get_bool("show_reply_context")
494 and $t->{in_reply_to_screen_name} ne $username
495 and $t->{in_reply_to_screen_name}
496 and not exists $friends{ $t->{in_reply_to_screen_name} } )
498 $nicks{ $t->{in_reply_to_screen_name} } = time;
499 my $context = $obj->show_status( $t->{in_reply_to_status_id} );
501 my $ctext = decode_entities( $context->{text} );
503 $ctext =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
504 printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
505 $context->{id}, $username,
506 $context->{user}{screen_name}, $ctext;
509 print "Failed to get context from $t->{in_reply_to_screen_name}"
514 if $t->{user}{screen_name} eq $username
515 and not Irssi::settings_get_bool("show_own_tweets");
516 printf $fh "id:%d account:%s nick:%s type:%s %s\n",
517 $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
520 print scalar localtime, " - Polling for replies" if &debug;
521 $tweets = $obj->replies( { since => HTTP::Date::time2str($last_poll) } )
523 foreach my $t ( reverse @$tweets ) {
525 if exists $friends{ $t->{user}{screen_name} };
527 my $text = decode_entities( $t->{text} );
529 $text =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
530 printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
531 $t->{id}, $username, $t->{user}{screen_name}, $text;
534 print scalar localtime, " - Polling for DMs" if &debug;
536 $obj->direct_messages( { since => HTTP::Date::time2str($last_poll) } )
538 foreach my $t ( reverse @$tweets ) {
539 my $text = decode_entities( $t->{text} );
541 $text =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
542 printf $fh "id:%d account:%s nick:%s type:dm %s\n",
543 $t->{id}, $username, $t->{sender_screen_name}, $text;
545 print scalar localtime, " - Done" if &debug;
550 my $filename = $data->[0];
552 print scalar localtime, " - checking child log at $filename" if &debug;
553 my $old_last_poll = $last_poll;
554 if ( open FILE, $filename ) {
558 last if /^__friends__/;
560 foreach my $key (qw/id account nick type/) {
565 next if exists $tweet_cache{$meta{id}};
566 $tweet_cache{$meta{id}} = time;
568 if ($meta{account} ne $user) {
569 $account = "$meta{account}: ";
571 if ($meta{type} eq 'tweet') {
572 push @lines, "[$account%B\@$meta{nick}%n] $_\n",
573 } elsif ($meta{type} eq 'reply') {
574 push @lines, "[$account\\--> %B\@$meta{nick}%n] $_\n",
575 } elsif ($meta{type} eq 'dm') {
576 push @lines, "[$account%B\@$meta{nick}%n (%%WDM%%n)] $_\n",
577 } elsif ($meta{type} eq 'debug') {
578 push @lines, "debug: $_\n" if &debug,
588 my ( $f, $t ) = split ' ', $_;
589 $nicks{$f} = $friends{$f} = $t;
592 if ( $last_poll != $old_last_poll ) {
593 print "new last_poll = $last_poll" if &debug;
594 foreach my $line (@lines) {
596 $window->print( $line, MSGLEVEL_PUBLIC );
597 foreach ( $line =~ /\@([-\w]+)/ ) {
604 or warn "Failed to remove $filename: $!"
607 # keep 10 minutes of cached tweets, to make sure we don't show duplicates.
608 foreach ( keys %tweet_cache ) {
609 next if $tweet_cache{$_} > time - 600;
610 delete $tweet_cache{$_};
617 Irssi::timeout_add_once( 5000, 'monitor_child', [$filename] );
621 return Irssi::settings_get_bool("twirssi_debug");
625 $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
629 my ( $complist, $window, $word, $linestart, $want_space ) = @_;
631 return unless $linestart =~ /^\/(?:tweet|dm)/;
632 my $prefix = $word =~ s/^@//;
633 $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
634 push @$complist, grep /^\Q$word/i,
635 sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
636 @$complist = map { "\@$_" } @$complist if $prefix;
639 Irssi::settings_add_str( "twirssi", "twitter_window", "twitter" );
640 Irssi::settings_add_str( "twirssi", "bitlbee_server", "bitlbee" );
641 Irssi::settings_add_str( "twirssi", "short_url_provider", "TinyURL" );
642 Irssi::settings_add_str( "twirssi", "twirssi_location",
643 ".irssi/scripts/twirssi.pl" );
644 Irssi::settings_add_str( "twirssi", "twitter_usernames", undef );
645 Irssi::settings_add_str( "twirssi", "twitter_passwords", undef );
646 Irssi::settings_add_bool( "twirssi", "tweet_to_away", 0 );
647 Irssi::settings_add_bool( "twirssi", "show_reply_context", 0 );
648 Irssi::settings_add_bool( "twirssi", "show_own_tweets", 1 );
649 Irssi::settings_add_bool( "twirssi", "twirssi_debug", 0 );
650 Irssi::settings_add_bool( "twirssi", "twirssi_first_run", 1 );
651 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
654 Irssi::command_bind( "dm", "cmd_direct" );
655 Irssi::command_bind( "tweet", "cmd_tweet" );
656 Irssi::command_bind( "dm_as", "cmd_direct_as" );
657 Irssi::command_bind( "tweet_as", "cmd_tweet_as" );
658 Irssi::command_bind( "twitter_login", "cmd_login" );
659 Irssi::command_bind( "twitter_logout", "cmd_logout" );
660 Irssi::command_bind( "twitter_switch", "cmd_switch" );
661 Irssi::command_bind( "twirssi_upgrade", "cmd_upgrade" );
665 print "twits: ", Dumper \%twits;
666 print "friends: ", join ", ", sort keys %friends;
667 print "nicks: ", join ", ", sort keys %nicks;
668 print "last poll: $last_poll";
675 "Twirssi v$VERSION (r$REV); Net::Twitter v$Net::Twitter::VERSION. "
676 . "See details at http://tinyurl.com/twirssi" );
682 "/twitter_friend <username>",
684 sub { ¬ice("Following $_[0]"); $nicks{ $_[0] } = time; }
690 "/twitter_unfriend <username>",
692 sub { ¬ice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
695 Irssi::command_bind( "twitter_updates", "get_updates" );
696 Irssi::signal_add_last( 'complete word' => \&sig_complete );
698 ¬ice(" %Y<%C(%B^%C)%N TWIRSSI v%R$VERSION%N (r$REV)");
699 ¬ice(" %C(_(\\%N http://twirssi.com/ for full docs");
701 " %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
703 if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
704 eval "use WWW::Shorten::$provider;";
708 "Failed to load WWW::Shorten::$provider - either clear short_url_provider or install the CPAN module"
713 if ( my $autouser = Irssi::settings_get_str("twitter_usernames")
714 and my $autopass = Irssi::settings_get_str("twitter_passwords") )
721 ->print( "Create a window named "
722 . Irssi::settings_get_str('twitter_window')
723 . " or change the value of twitter_window. Then, reload twirssi." );